mongodb-如何查找然后聚合


74

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

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

架构:

{
"_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
}

请帮忙...

Answers:


131

您必须使用$ match

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

输出:

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

3
['!all']代表什么?
cafebabe1991 '16

1
我只是从问题中复制了该代码。“!all”似乎是集合名称,但与答案本身无关
Enrique Fueyo 2016年

[!all]是否表示所有集合?
cafebabe1991

2
不,我不这么认为
Enrique Fueyo

10
[!all]应该表示NOT ALL,这是命名集合的一种奇怪方法;)
c24b

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} } }
])

1

如果需要将DOB编号转换为Date然后进行比较,这是一个答案。如果不是,则数字或日期(例如1970)将错误地$ gte转换为19400801(可以尝试):

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" }
        }
    }
])

输出:

{ "_id" : "F", "totalscore" : 109 }
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.