如何在java中使用mongodb$组?

How to use mongodb $group in java?

我在 MongoDB 中处理了一个集合 processedClickLog。

{
        "_id" : ObjectId("58ffb4cefbe21fa7896e2d73"),
        "ID" : "81a5d7f48e5df09c9bc006e7cc89d6e6",
        "USERID" : "206337611536",
        "DATETIME" : "Fri Mar 31 17:29:34 -0400 2017",
        "QUERYTEXT" : "Tom",
        "DOCID" : "www.demo.com",
        "TITLE" : "Harry Potter",
        "TAB" : "People-Tab",
        "TOTALRESULTS" : "1",
        "DOCRANK" : 1
}
{      "id":
        ....
}

我正在尝试在 java 中执行一个复杂的查询。我的查询是获取 processedClickLog 集合,其中

  1. TAB 不等于人物-Tab
  2. DOCRANK 不等于 0
  3. 仅 return "USERID"、"DOCID"、"DOCRANK"、"QUERYTEXT" 字段
  4. 按 USERID 分组

下面是我的 Java 代码。我能够满足前三个条件。但我被困在按 USERID 分组的第 4 个条件上。

String jsonResult = "";
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        MongoDatabase database = mongoClient.getDatabase("test1");
        MongoCollection<Document> collection = database.getCollection("processedClickLog");
        //add condition where TAB is not equal to "People-Tab" and DOCRANK is not equal to 0
        List<DBObject> criteria = new ArrayList<DBObject>();
        criteria.add(new BasicDBObject("DOCRANK", new BasicDBObject("$ne", 0)));
        criteria.add(new BasicDBObject("TAB", new BasicDBObject("$ne", "People-Tab")));

            //combine the above two conditions
            BasicDBObject query = new BasicDBObject("$and", criteria);
            //to retrieve all the documents with specific fields 
            MongoCursor<Document> cursor = collection.find(query)
                    .projection(Projections.include("USERID", "DOCID", "DOCRANK", "QUERYTEXT")).iterator();
      try {
                while (cursor.hasNext()) {
                    System.out.println(cursor.next().toJson());

                }
            } finally {
                cursor.close();
            }
            System.out.println(hashMap);
            mongoClient.close();
    }

我应该如何定义整个查询以在 java 中添加条件 "group by USERID"?感谢任何帮助

您必须使用聚合框架。静态导入 helper classes 的所有方法并使用下面的代码。

在较新的 3.x 驱动程序 api 中不需要使用 BasicDBObject。您应该使用新的 class 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.*;

Bson match = match(and(ne("DOCRANK", 0), ne("TAB", "People-Tab")));
Bson group = group("$USERID", first("USERID", "$USERID"), first("DOCID", "$DOCID"), first("DOCRANK", "$DOCRANK"), first("QUERYTEXT", "$QUERYTEXT"));
Bson projection = project(fields(include("USERID", "DOCID", "DOCRANK", "QUERYTEXT"), excludeId()));
MongoCursor<Document> cursor = collection.aggregate(asList(match, group, projection)).iterator();

投影阶段是可选的,只是为了给出一个完整的例子而添加的。

这里有更多关于聚合的信息https://docs.mongodb.com/manual/reference/operator/aggregation/