mongodb - how to find and then aggregate

前端 未结 3 1370
忘了有多久
忘了有多久 2021-02-01 11:39

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

相关标签:
3条回答
  • 2021-02-01 12:25

    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 }
    
    0 讨论(0)
  • 2021-02-01 12:27

    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} } }
    ])
    
    0 讨论(0)
  • 2021-02-01 12:29

    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 讨论(0)
提交回复
热议问题