簡體   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