Mongodb sums the size of the fields of an array

so I have a bunch of simple documents like

{ "foos": [ ObjectId("5105862f2b5e30877c685c58"), ObjectId("5105862f2b5e30877c685c57"), ObjectId("5105862f2b5e30877c685c56"), ], "typ": "Organisation", } 

and I want to know the total size of the associated foos with documents of type "Organization"

so I have this general request

 db.profil.aggregate( [ { $match:{ "typ":"Organisation" } }, { $project: { fooos: { $size: "$foos" } } } ] ) 

this returns the number of all foos for each document

like:

 { "_id" : ObjectId("50e577602b5e05e74b38a6c8"), "foooos" : 1 } { "_id" : ObjectId("51922170975a09f363e3eef5"), "foooos" : 3 } { "_id" : ObjectId("51922170975a09f363e3eef8"), "foooos" : 2 } { "_id" : ObjectId("5175441d975ae346a3a8dff2"), "foooos" : 0 } { "_id" : ObjectId("5192216f975a09f363e3eee9"), "foooos" : 2 } { "_id" : ObjectId("5192216f975a09f363e3eeeb"), "foooos" : 3 } { "_id" : ObjectId("5192216f975a09f363e3eee4"), "foooos" : 2 } { "_id" : ObjectId("5192216f975a09f363e3eee6"), "foooos" : 2 } { "_id" : ObjectId("5192216f975a09f363e3eedb"), "foooos" : 2 } { "_id" : ObjectId("51922174975a09f363e3ef4a"), "foooos" : 1 } { "_id" : ObjectId("5192216f975a09f363e3eee1"), "foooos" : 1 } { "_id" : ObjectId("5192216e975a09f363e3eed7"), "foooos" : 2 } { "_id" : ObjectId("5192216f975a09f363e3eeee"), "foooos" : 3 } 

Is there any query that will return a calculation of the amounts for all documents?

I played arround with $ sum, but I don’t know how to combine with my request, I only get syntax errors, it would be great to know if this is possible

+7
mongodb
source share
2 answers

Turn on the $group step after $project follow these steps:

 db.profil.aggregate([ { "$match":{ "typ": "Organisation" } }, { "$project": { "fooos": { "$size": "$foos" } } }, { "$group": { "_id": null, "count": { "$sum": "$fooos" } } } ]) 

This will group all input documents from the previous stage of $project and apply the accumulator expression $sum in the fooos field inside the group to get the total (using the last example):

Exit

 /* 0 */ { "result" : [ { "_id" : null, "count" : 24 } ], "ok" : 1 } 
+16
source share

I know this is an old question, but can you get around the project in general if you want, so how about this?

 db.profil.aggregate([ { "$match":{ "typ": "Organisation" } }, { "$group": { "_id": null, "count": { "$sum": { "$size": "$foos" } } } }]) 

The output remains the same, and it seems to be (slightly) faster.

+6
source share

All Articles