mongodb - 如何查找然后聚合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25436630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
mongodb - how to find and then aggregate
提问by hello mtyj
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
}
Please help...
请帮忙...
回答by Enrique Fueyo
回答by Binita Bharati
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} } }
])
回答by Yi Xiang Chong
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):
如果需要将 DOB 数字转换为日期然后进行比较,这里是一个答案。如果不是,数字或日期如 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" }
}
}
])
Outputs:
输出:
{ "_id" : "F", "totalscore" : 109 }