使用Java驱动程序

时间:2018-02-06 15:35:36

标签: 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" },
        "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");

由于

1 个答案:

答案 0 :(得分:0)

在您的问题中,MongoDB Java驱动程序等效于MongoDB shell命令:

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等效项之间的转换。