MongoDB聚合排序不起作用

编程入门 行业动态 更新时间:2024-10-25 02:30:52
本文介绍了MongoDB聚合排序不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在对聚合分组应用排序时遇到问题.我的原始数据如下所示:

I'm having a problem applying a sort to an aggregation grouping. My raw data looks like the following:

{ "_id" : ObjectId("52deab2fe4b0a491abb54108"), "type" : "build", "time" : ISODate("2014-01-21T17:15:27.471Z"), "data" : { "buildNumber" : 43, "buildDuration" : 997308, "buildProjectName" : "TestABC", "buildResult" : "SUCCESS" } }

我想先按buildProjectName排序,然后按日期排序.这是我的查询:

I would like to sort this first by buildProjectName and then date. Here is my query:

db.builds.aggregate([ { $group: { _id: { month: { $month: "$time" }, day: { $dayOfYear: "$time" }, year: { $year: "$time" }, buildProjectName: "$data.buildProjectName", }, buildDuration: { $avg: "$data.buildDuration" } } }, { $sort: {buildProjectName: 1, year: 1, month: 1, day: 1} } ])

我尝试过切换排序顺序(即:buildProjectName,日,月,年),但是我总是得到相同的结果,但日期却乱了:

I've tried switching the order of the sort (i.e.: buildProjectName, day, month, year), but I always get the same result with the dates out of order:

{ "result" : [ { "_id" : { "month" : 1, "day" : 20, "year" : 2014, "buildProjectName" : "TestABC" }, "buildDuration" : 1170723.5 }, { "_id" : { "month" : 1, "day" : 21, "year" : 2014, "buildProjectName" : "TestABC" }, "buildDuration" : 2284863.3333333335 }, { "_id" : { "month" : 1, "day" : 17, "year" : 2014, "buildProjectName" : "TestABC" }, "buildDuration" : 2234662 } ], "ok" : 1 }

推荐答案

要排序的字段是_id的一部分,因此您需要在$sort字段名称中包括该字段:

The fields you're sorting on are part of the _id so you need to include that in your $sort field names:

db.builds.aggregate([ { $group: { _id: { month: { $month: "$time" }, day: { $dayOfYear: "$time" }, year: { $year: "$time" }, buildProjectName: "$data.buildProjectName", }, buildDuration: { $avg: "$data.buildDuration" } } }, { $sort: { '_id.buildProjectName': 1, '_id.year': 1, '_id.month': 1, '_id.day': 1 } } ])

更多推荐

MongoDB聚合排序不起作用

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

发布评论

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

>www.elefans.com

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