Gib*_*bbs 6 java mongodb morphia
我有以下几种类型的请求。
server/controllerName/access_id/id/field/field_value/api_name
server/controllerName/access_id/id/field/field_value/field2/field_value/api_name
Run Code Online (Sandbox Code Playgroud)
几个字段示例:
1. start date and end date
2. user name
3. user group
Run Code Online (Sandbox Code Playgroud)
Mongo DB数据格式:
Mongo DB存储用户订单详细信息。每个订单包含用户详细信息[10个字段]和订单详细信息[30个字段]
如果未提及日期,则API必须默认提供最近30天的订单。
我的问题:
如何有效地从mongo db读取此数据?
我目前正在做什么:
我正在解析httprequest并将这些字段添加到map
{"name":"gibbs", "category":"vip"}
Run Code Online (Sandbox Code Playgroud)
我必须获取这两个字段匹配的所有文档,并以以下形式返回文档。
{
user: "gibbs",
total_Result: 10,
[
{
//order details items from doc 1
}
{
//order details from doc2
}
]
}
Run Code Online (Sandbox Code Playgroud)
我正在查询mongo db,如下所示。
MongoCollection<Document> mongoEngCollection = mongoDbReader.getCollection();
BasicDBObject andQuery = new BasicDBObject();
List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
//Forming query using request parameter. requestAttributes contains map of request parameters.
for(Map.Entry<PathAttribute, PathValue<?>> entry : requestAttributes.entrySet()) {
String key = entry.getKey().getName();
obj.add(new BasicDBObject(key, entry.getValue().getRawValue()));
}
andQuery.put("$and", obj);
//Queryng mongo db
FindIterable<Document> documents = mongoEngCollection.find(andQuery);
Run Code Online (Sandbox Code Playgroud)
然后,我要遍历文档并将字段分组为所需格式。
它是使用spring编写的。
我对模式更改,查询更改,注释方法都很好,只要它非常快且在概念上正确即可。
请给我提意见。
您必须使用聚合框架。静态导入辅助类的所有方法并使用以下代码。
BasicDBObject在较新的 3.x 驱动程序 api 中不推荐使用。您应该使用新类Document来满足类似的需求。
import static com.mongodb.client.model.Accumulators.*;
import static com.mongodb.client.model.Aggregates.*;
import static java.util.Arrays.asList;
import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Projections.*;
import org.bson.conversions.Bson;
MongoCollection<Document> mongoEngCollection = mongoDbReader.getCollection();
List<Bson> obj = new ArrayList<>();
//Forming query using request parameter. requestAttributes contains map of request parameters.
for(Map.Entry<PathAttribute, PathValue<?>> entry : requestAttributes.entrySet()) {
String key = entry.getKey().getName();
//Check if key is not date and set the start and end date
obj.add(eq(key, entry.getValue().getRawValue()));
}
//Build aggregation stages
Bson match = match(and(obj));
Bson group = group(
first("user", "$name"),
sum("total_results", 1),
push("results", "$$ROOT")
);
Bson projection = project(fields(excludeId()));
//Query Mongodb
List<Document> results = mongoEngCollection .aggregate(asList(match, group, projection)).into(new ArrayList<Document>());
Run Code Online (Sandbox Code Playgroud)
有关聚合的更多信息,请参见https://docs.mongodb.com/manual/reference/operator/aggregation/
| 归档时间: |
|
| 查看次数: |
156 次 |
| 最近记录: |