简体   繁体   English

从mongodb访问数据

[英]Accessing data from mongodb

I have the following types of requests . 我有以下类型的请求

server/controllerName/access_id/id/field/field_value/api_name
server/controllerName/access_id/id/field/field_value/field2/field_value/api_name

Few field examples: 几个领域的例子:

1. start date and end date
2. user name
3. user group

Mongo DB data format: Mongo DB数据格式:

Mongo DB stores user order details. Mongo DB存储用户订单详细信息。 Each order contains user detail[10 fields] and order details[30 fields] 每个订单包含用户详细信息[10个字段]和订单详细信息[30个字段]

API has to give by default last 30 days of orders if no date is mentioned. 如果没有提及日期,API必须默认提供最后30天的订单。

My question: 我的问题:

How can I efficiently read this data from mongo db? 如何从mongo db有效地读取这些数据?

What I am currently doing: 我目前在做什么:

I am parsing the httprequest and adding these fields to a map 我正在解析httprequest并将这些字段添加到map

{"name":"gibbs", "category":"vip"}

I have to get all the documents where these two fields are matching and return the documents in the following form. 我必须得到这两个字段匹配的所有文档,并以下面的形式返回文档。

{
 user: "gibbs",
 total_Result: 10,
 [
  {
   //order details items from doc 1
  }
  {
   //order details from doc2
  }
 ]
 }

I am querying mongo db as follows. 我按如下方式查询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);

Then I am iterating the documents and grouping the fields as the required format. 然后我迭代文档并将字段分组为所需的格式。

It is written using spring. 它是用春天写的。

I am fine with schema changes, query changes, annotation methods as long as it is very fast and conceptually correct. 我可以使用模式更改,查询更改,注释方法,只要它非常快且概念上正确。

Please advise me. 请建议我。

You've to use aggregation framework. 您将使用聚合框架。 Statically import all the methods of helper classes and use the below code. 静态导入辅助类的所有方法并使用下面的代码。

Use of BasicDBObject is deprecated in newer 3.x driver api. 在较新的3.x驱动程序api中不推荐使用BasicDBObject You should use the new class Document for similar needs. 您应该使用新类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>());

More about aggregation here https://docs.mongodb.com/manual/reference/operator/aggregation/ 有关聚合的更多信息,请访问https://docs.mongodb.com/manual/reference/operator/aggregation/

This can be achieved using Projections and Lookups in MongoDB. 这可以使用MongoDB中的Projections和Lookup来实现。 Apply self joins https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/ Limit what to bring https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/ 应用自联接https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/限制带来的内容https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results /

I hope you can figure out easily how to write the query. 我希望你能轻易弄清楚如何编写查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM