java - MongoDB aggregation result as a nested Json -


this piece of 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 } } 

. . and, goes.

what need each unique "id", sum of "i"'s, "x"'s , "info.j"'s. able :

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

with output :

{ "_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 } 

so far, looks perfect. except for, cant keep "j" in output nested object inside "info" in original collection. can ?

thanks.

the aggregation frameork requires field names used in accumulators single name, next argument presumed accumulator in structre. nor can use "dot notation" invalid.

the thing $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")                 ))         ) )); 

or of course process each result , alter bson structure there in same way.


Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

Nuget pack csproj using nuspec -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -