MongoDB 作为嵌套的聚合结果 Json

MongoDB aggregation result as a nested Json

这是我的 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 }

到目前为止,一切看起来都很完美。除了,我无法像原始 collection 那样将输出中的 "j" 作为嵌套 object 保留在 "info" 中。我能做什么?

谢谢。

聚合框架要求累加器中使用的所有字段名称都是单个名称,因为下一个参数被假定为结构中的累加器本身。你也不能使用 "dot notation" 因为这也是无效的。

唯一要做的就是$project:

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("i",1)
                .append("x", new Document("x",1)),
                .append("x", new Document("info",
                   new Document("j", "$j")
                ))
        )
));

或者当然只是简单地处理每个结果并以几乎相同的方式改变那里的 BSON 结构。

请尝试以下操作:

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")))
    ));