gpt4 book ai didi

java - 如何在java中使用mongodb $group?

转载 作者:行者123 更新时间:2023-12-01 20:27:45 24 4
gpt4 key购买 nike

我在 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 不等于 People-Tab
  2. DORANK 不等于 0
  3. 仅返回“USERID”、“DOCID”、“DOCRANK”、“QUERYTEXT”字段
  4. 按 USERID 分组

下面是我的Java代码。我能够满足前三个条件。但我陷入了第四个条件,即按 USERID 分组。

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”?感谢任何帮助

最佳答案

您必须使用聚合框架。静态导入辅助类的所有方法并使用以下代码。

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

关于java - 如何在java中使用mongodb $group?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43646407/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com