这是我的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"one_answers"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")))
));
聚合框架要求累加器中使用的所有字段名都是一个名称,因为下一个参数被假定为结构中的累加器本身。也不能使用"点表示法",因为这也是无效的。
唯一要做的就是 $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结构。