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

使用Java驱动程序的MongoDB聚合代码,java,mongodb,mongodb-query,aggregation-framework,mongodb-java,Java,Mongodb,Mongodb Query,Aggregation Framework,Mongodb Java,我很难将MongoDB聚合查询转换为Java。我可以在Mongo shell中得到结果,但不能在Java中得到结果 db.intentAnalysisPojo.aggregate( {"$match": { "threadId": "f5683604-9fc8-40dd-9b7b-a1ef8e3bdb02"} }, { "$group": { "_id":"$question", "answer": { "$first": "$answer" }

我很难将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 此代码故意使用新文档$group。。。习惯用法,而不是Aggregates.group实用程序,以帮助澄清shell命令和Java等效命令之间的转换。