java - MongoDB 聚合结果作为嵌套 Json

标签 java mongodb aggregation-framework mongo-java-driver

这是我的 MongoDB Collection 的一部分:

{ "_id" : ObjectId("55b0ba203a20b54e3b1e09e4"), "i" : 0, "x" : 1, "id" : 2, "info" : { "j" : 0 } }
{ "_id" : ObjectId("55b0ba203a20b54e3b1e09e5"), "i" : 1, "x" : 2, "id" : 2, "info" : { "j" : 1 } }
{ "_id" : ObjectId("55b0ba203a20b54e3b1e09e6"), "i" : 2, "x" : 3, "id" : 2, "info" : { "j" : 2 } }
{ "_id" : ObjectId("55b0ba203a20b54e3b1e09e7"), "i" : 3, "x" : 4, "id" : 2, "info" : { "j" : 3 } }
{ "_id" : ObjectId("55b0ba203a20b54e3b1e09e8"), "i" : 4, "x" : 5, "id" : 2, "info" : { "j" : 4 } }
{ "_id" : ObjectId("55b0ba203a20b54e3b1e09e9"), "i" : 5, "x" : 6, "id" : 2, "info" : { "j" : 5 } }
{ "_id" : ObjectId("55b0ba203a20b54e3b1e09ea"), "i" : 6, "x" : 7, "id" : 2, "info" : { "j" : 6 } }
{ "_id" : ObjectId("55b0ba203a20b54e3b1e09eb"), "i" : 7, "x" : 8, "id" : 2, "info" : { "j" : 7 } }
{ "_id" : ObjectId("55b0ba203a20b54e3b1e09ec"), "i" : 8, "x" : 9, "id" : 2, "info" : { "j" : 8 } }
{ "_id" : ObjectId("55b0ba203a20b54e3b1e09ed"), "i" : 9, "x" : 10, "id" : 2, "info" : { "j" : 9 } }

。 。 而且,事情就这样发生了。

我需要做的是对于每个唯一的“id”,获取所有“i”、“x”和“info.j”的总和。我完全能够做到这一点:

AggregateIterable<Document> iterable = collection.aggregate(Arrays.asList(
        new Document("$group", new Document("_id", "$id")
                .append("i", new Document("$sum", "$i"))
                .append("x", new Document("$sum", "$x"))
                .append("j", new Document("$sum", "$info.j")))));

输出为:

{ "_id" : 3, "i" : 49995000, "x" : 50005000, "id" : 3, "j" : 49995000 }
{ "_id" : 1, "i" : 99990000, "x" : 100010000, "id" : 1, "j" : 99990000 }
{ "_id" : 2, "i" : 49995000, "x" : 50005000, "id" : 2, "j" : 49995000 }

到目前为止,一切看起来都很完美。除此之外,我无法像原始集合中那样将输出中的“j”保留为“info”内的嵌套对象。我能做什么?

谢谢。

最佳答案

请尝试以下操作:

AggregateIterable<Document> iterable = collection.aggregate(
Arrays.asList(
    new Document("$group", new Document("_id", "$id")
            .append("i", new Document("$sum", "$i"))
            .append("x", new Document("$sum", "$x"))
            .append("j", new Document("$sum", "$info.j"))),
    new Document("$project",new Document("_id","$_id").
           .append("i","$i")
           .append("x",  "$x")
           .append("info", new Document("j", "$j")))
    ));

关于java - MongoDB 聚合结果作为嵌套 Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31587340/

相关文章:

java - 当我们有Rest API来调用不同的应用程序时,为什么还要使用jitterbit或informatica等集成工具?

mongodb - 将包含大量数据的 mongo 集合复制到另一个集合?

javascript - 比较三个日期以获得最新的 MongoDB

mongodb - 左连接 mongodb laravel

javascript - MongoDB( Mongoose )集合中特定 ObjectID 的聚合计数实例

java - 在java中将字符串写入字节数组

java - 如何在maven eclipse项目中使用cplex.jar?

java - 以编程方式关闭 jetty 客户端

python - 我在从 mongodb 查询数据并渲染到 Flask 时遇到问题

java - 根据条件删除重复项