117

I have collection that contains documents with below schema. I want to filter/find all documents that contain the gender female and aggregate the sum of brainscore. I tried the below statement and it shows a invalid pipeline error.

db['!all'].aggregate({ $and: [ {'GENDER' :  'F'} , {'DOB' : { $gte : 19400801, $lte : 20131231 }} ]  }, { $group : { _id : "$GENDER", totalscore : { $sum : "$BRAINSCORE" } } } )

Schema:

{
    "_id" : ObjectId("53f63fc8f2b643f6ebb8a1a9"),
    "DOB" : 19690112,
    "GENDER" : "F",
    "BRAINSCORE" : 65
},
{
    "_id" : ObjectId("53f63fc8f2b643f6ebb8a1a2"),
    "DOB" : 19950116,
    "GENDER" : "F",
    "BRAINSCORE" : 44
},
{
    "_id" : ObjectId("53f63fc8f2b643f6ebb8a902"),
    "DOB" : 19430216,
    "GENDER" : "M",
    "BRAINSCORE" : 71
}

4 Answers 4

188

You have to use $match:

db['!all'].aggregate([
  {$match:
    {'GENDER': 'F',
     'DOB':
      { $gte: 19400801,
        $lte: 20131231 } } },
  {$group:
     {_id: "$GENDER",
     totalscore:{ $sum: "$BRAINSCORE"}}}
])

Outputs:

{ "_id" : "F", "totalscore" : 109 }
6
  • 3
    what does ['!all'] stand for ? Jun 2, 2016 at 4:28
  • 1
    I just copied that code from the question. '!all' seems to be the collection name but not related to the answer itself Jun 2, 2016 at 15:16
  • 2
    No, I dont think so Jun 2, 2016 at 15:41
  • 13
    [!all] should means NOT ALL and it is a strange way to name a collection ;)
    – c24b
    Apr 11, 2017 at 15:34
  • 1
    If you want to aggregate using a user's id, (which is a mongoose objectID), you need to cast your query id (which is of type string) to mongoose objectID. Thus: const userId = mongoose.Types.ObjectId(user_id). Else, $match it will return an empty array.
    – Austin
    Oct 11, 2021 at 12:31
6

Sample working query :

db.getCollection('NOTIF_EVENT_RESULT').aggregate([
{$match:
    {'userId': {'$in' : ['user-900', 'user-1546']},
    'criteria.operator': 'greater than', 'criteria.thresold' : '90', 'category' : 'capacity'}
},
{"$group" :  {_id : {userId:"$userId"}, "count" : { "$sum" : 1} } }
])
3

Here is an answer if the DOB numbers needs to be converted to Date then compared. If not, a number or Date such as 1970 will be incorrectly $gte to 19400801 (you can try):

db['!all'].aggregate([
    {
        $addFields: {
            "_temp_DOB": {
                $dateFromString: {
                    dateString: {$toString: {$toLong: "$DOB"}},
                    format: "%Y%m%d"
                }
            }
        }   
    },
    {
        $match: {
            'GENDER': 'F', 
            '_temp_DOB': { $gte: new Date("1940-08-01"),  
                           $lte: new Date("2013-12-31") }
        }
    },
    {
        $group: {
            _id: "$GENDER", 
            totalscore: { $sum: "$BRAINSCORE" }
        }
    }
])

Outputs:

{ "_id" : "F", "totalscore" : 109 }
0

In addition to Enrique's answer,

If you want to aggregate using a user's id, (which is a mongoose objectID), you need to cast your query id (which is of type string) to mongoose objectID. Thus:

const userId = mongoose.Types.ObjectId(user_id). 

Else, $match it will return an empty array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.