本文介绍了带有条件组和另一个字段的 Mongo 查询聚合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我关注了@Blakes-Seven 的这篇文章Mongodb 聚合多个日期范围的 $group
I followed this post by @Blakes-Seven Mongodb aggregate $group for multiple date ranges
但我需要按字段$User.Account"添加一个额外的组,但我不断收到错误消息.当我把它拿出来时,它工作正常.
But I need to add an additional group by field "$User.Account" and I keep getting an error. When I take that out it works fine.
我正在尝试做的并且我很确定下面不会做的是找到每个日期范围内的前 N 个用户...
What I'm trying to do and I'm pretty sure the below won't do it is find the top N users within each of the date ranges...
{ "message" : "the group aggregate field 'User' must be defined as an expression inside an object", "ok" : 0, "code" : 15951, "name" : "MongoError" }任何帮助将不胜感激.我错过了一些东西...
Any help would be greatly appreciated. I'm missing something...
> // 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 推荐答案您可以按照以下语法在 $group 表达式中添加另一个字段
You can follow below syntax to add another field in $group expression
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} ])更多推荐
带有条件组和另一个字段的 Mongo 查询聚合
发布评论