繁体   English   中英

使用 Java 驱动程序的 MongoDB 聚合代码

[英]MongoDB aggregation code using the Java driver

我很难将 MongoDB 聚合查询转换为 Java。 我能够在 Mongo shell 中得到结果,但在 Java 中却不能得到结果......

db.intentAnalysisPojo.aggregate(
    {"$match": { "threadId": "f5683604-9fc8-40dd-9b7b-a1ef8e3bdb02"} },
    { "$group": {
        "_id":"$question", 
        "answer": { "$first": "$answer" },
        "intent": { "$first": "$intent" },
        "wdsAns1":{"$first": "$wdsAns1"},
        "wdsAns2":{"$first": "$wdsAns2"},
        "wdsAns3":{"$first": "$wdsAns3"},
        }},
    { "$sort" : { "intent" : 1}}
);

我试过这个 Java 代码,但它不起作用......

Document firstGroup = new Document("$group",
    new Document("_id", "$question")
        .append("$first", "$answer")
        .append("$first", "$intent")
        .append("$first", "$wdsAns1")
        .append("$first", "$wdsAns2")
        .append("$first", "$wdsAns3"));

AggregationOperation match = Aggregation.match(Criteria.where("threadId").is(uuid));

AggregationOperation group = Aggregation.group(firstGroup.toJson());

AggregationOperation sort = Aggregation.sort(Sort.Direction.ASC, "intent");

谢谢

这是与您的问题中的 MongoDB shell 命令等效的 MongoDB Java 驱动程序:

MongoClient mongoClient = ...;

MongoCollection<Document> collection = mongoClient.getDatabase("...").getCollection("...");

List<Document> documents = collection.aggregate(Arrays.asList(
        // {"$match": { "threadId": "f5683604-9fc8-40dd-9b7b-a1ef8e3bdb02"} }
        Aggregates.match(new Document("threadId", "f5683604-9fc8-40dd-9b7b-a1ef8e3bdb02")),

        // { "$group": { "_id":"$question", "answer": { "$first": "$answer" }, "intent": { "$first": "$intent" }, "wdsAns1":{"$first": "$wdsAns1"}, "wdsAns2":{"$first": "$wdsAns2"}, "wdsAns3":{"$first": "$wdsAns3"} }}
        new Document("$group",
                new Document("_id", "$question")
                        .append("answer", new Document("$first", "$answer"))
                        .append("intent", new Document("$first", "$intent"))
                        .append("wdsAns1", new Document("$first", "$wdsAns1"))
                        .append("wdsAns2", new Document("$first", "$wdsAns2"))
                        .append("wdsAns3", new Document("$first", "$wdsAns3"))
        ),

        // { "$sort" : { "intent" : 1} }
        Aggregates.sort(new Document("$sort", new Document("intent", new BsonInt32(1)))))
).into(new ArrayList<>());

for (Document document : documents) {
    logger.info("{}", document.toJson());
}

笔记:

  • 这是使用 Java 驱动程序的 v3.x
  • 此代码特意使用new Document("$group", ...)习惯用法而不是Aggregates.group()实用程序来帮助阐明 shell 命令和 Java 等效项之间的转换。

暂无
暂无

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

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