Home > other >  Sum int values of an array field
Sum int values of an array field

Time:12-19

I have a records collection with thousands of documents, like the following:

{ "_id" : ObjectId("5ee1e209e07f053f990cea8c"), "key" : "TAKwGc6Jr4i8Z487", "createdAt" : ISODate("2017-01-28T01:22:14.398Z"), "counts" : [ 150, 160 ], "value" : "Doc1" }
{ "_id" : ObjectId("5ee1e8dee07f053f990ceaa1"), "key" : "TAKwGc6Jr4i8Z487", "createdAt" : ISODate("2017-01-28T01:22:14.398Z"), "counts" : [ 170 ], "value" : "Doc2" }
...

I want to write a query to select them by date range, and by the total count of elements in the counts array field.

I haven't managed to find any resources on that. Should an aggregation be used, in this case?

Like $sum something?

{$and:[
  {createdAt:{$gte:ISODate('2016-01-30'),$lt:ISODate('2016-02-01')}},
  {<sum> ???}
]}

CodePudding user response:

You can add a field to calculate sum of counts using $addFields, then use $match to compare sum and finally remove that temporary field before return using $unset.
Here is the playground for your example.

  • Related