当前位置: 代码迷 >> java >> MongoDB聚合结果作为嵌套Json
  详细解决方案

MongoDB聚合结果作为嵌套Json

热度:52   发布时间:2023-08-02 10:52:11.0

这是我的MongoDB集合的一部分:

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

聚合框架要求所有在累加器中使用的字段名称必须是单个名称,因为下一个参数假定是结构体中的累加器本身。 您也不能使用“点符号”,因为这也是无效的。

唯一要做的是 :

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结构。

  相关解决方案