我在此帖子之后@ Blakes-Seven Mongodb aggregate $group for multiple date ranges
但是我需要通过“ $ User.Account”字段添加一个附加组,并且不断收到错误消息。当我取出来时,效果很好。
我正在尝试做的事,我很确定下面的事情不会在每个日期范围内找到前N名用户...
{
"message" : "the group aggregate field 'User' must be defined as an expression inside an object",
"ok" : 0,
"code" : 15951,
"name" : "MongoError"
}
任何帮助将不胜感激。我想念一些东西...
> // work out dates somehow var today = new Date(),
> oneDay = ( 1000 * 60 * 60 * 24 ),
> ninetyDays = new Date( today.valueOf() - ( 90 * oneDay ) ),
> sixtyDays = new Date( today.valueOf() - ( 60 * oneDay ) ),
> thirtyDays = new Date( today.valueOf() - ( 30 * oneDay ) );
>
> db.logs.aggregate([
> { "$match": {
> "DateTime": { "$gte": ninetyDays },
> "Orgname": /Inc/
> }},
> { "$group": {
> "_id": {
> "$cond": [
> { "$lt": [ "$DateTime", sixtyDays ] },
> "61-90",
> { "$cond": [
> { "$lt": [ "$DateTime", thirtyDays ] },
> "31-60",
> "01-30"
> ]}
> ]
> },
> "User": "$User.Account",
> "count": { "$sum": 1 },
> }},
> { $sort: {"count": -1}
> },
> { $limit: 25} ])
Sample output
01-30 usera 45
01-30 userc 34
01-30 userf 28
01-30 userq 13
… 20 more rows...
01-30 usery 4
31-60 userb 55
… 23 more rows
31-60 userk 3
61-90 userm 78
61-90 userf 45
... 22 more rows...
61-90 usery 22
答案 0 :(得分:1)
您可以按照以下语法在$group
表达式中添加另一个字段
db.logs.aggregate([
{ "$match": {
"DateTime": { "$gte": ninetyDays },
"Orgname": /Inc/
}},
{ "$group": {
"_id": {
"User": "$User.Account",
"date": {
"$cond": [
{ "$lt": [ "$DateTime", sixtyDays ] },
"61-90",
{ "$cond": [
{ "$lt": [ "$DateTime", thirtyDays ] },
"31-60",
"01-30"
]}
]
}
},
"count": { "$sum": 1 },
}},
{ "$sort": { "count": -1 }},
{ "$limit": 25}
])