带有条件组和另一个字段的 Mongo 查询聚合

编程入门 行业动态 更新时间:2024-10-27 16:25:44
本文介绍了带有条件组和另一个字段的 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 查询聚合

本文发布于:2023-11-22 04:12:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1615935.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   条件   Mongo

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!