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”中。我能做些什么 ?

谢谢。

4

2 回答 2

2

请尝试以下方法:

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")))
    ));
于 2015-07-23T12:40:21.673 回答
1

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

唯一要做的是$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 结构。

于 2015-07-23T12:36:17.280 回答