MongoDBのデータへのアクセス

ギブス:

私は以下の持っている要求のタイプを

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

いくつかのフィールドの例:

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

モンゴDBデータ・フォーマット:

モンゴDBは、ユーザーの注文の詳細を格納します。各順序は、ユーザ詳細[10のフィールド]と注文の詳細を含む[30のフィールド】

APIには、日付が言及されていない場合は注文のデフォルト最後の30日間で与えることがあります。

私の質問:

どうすれば効率的にモンゴDBからこのデータを読み取ることができますか?

私は現在、何をやっています:

私はパースしていますhttprequestし、これらのフィールドを追加しますmap

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

私はこれらの2つのフィールドが一致しているすべての文書を取得し、次の形式で文書を返すことがあります。

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

私はモンゴデシベル以下のように照会しています。

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);

それから私は、ドキュメントを反復し、必要な形式などのフィールドをグループ化しています。

これは、スプリングを使用して書かれています。

私は、スキーマの変更、クエリの変更、長いそれは非常に高速で、概念的に正しいとして注釈方法に元気です。

私に助言してください。

user2683814:

あなたは、集約フレームワークを使用してきました。静的ヘルパークラスのすべてのメソッドをインポートして、以下のコードを使用します。

使用は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>());

もっとここに集約についてhttps://docs.mongodb.com/manual/reference/operator/aggregation/

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=226334&siteId=1