mongodb - 如何找到然后聚合

hel*_*tyj 59 mongodb

我的集合包含以下架构的文档.我想过滤/查找包含性别女性的所有文档,并汇总brainscore的总和.我尝试了以下语句,它显示了无效的管道错误.

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

架构:

{
"_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
}
Run Code Online (Sandbox Code Playgroud)

请帮忙...

Enr*_*eyo 110

你必须使用$ match:

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

输出:

{ "_id" : "F", "totalscore" : 109 }
Run Code Online (Sandbox Code Playgroud)

  • [!all]应该意味着并非全部,这是一种命名集合的奇怪方式;) (10认同)
  • ['!all']代表什么? (3认同)
  • 不,我不这么认为 (2认同)

Bin*_*ati 6

工作查询样例:

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} } }
])
Run Code Online (Sandbox Code Playgroud)