排序聚合addToSet结果 [英] Sorting aggregation addToSet result
问题描述
有没有一种方法可以获取$ addToSet的结果作为排序数组?
Is there a way to get result of $addToSet as sorted array ?
我尝试扩展管道并展开数组,对其进行排序并再次将其分组, 但结果仍未排序.
I tried to expand the pipeline and $unwind the array, sort it and group it again , but still the result isn't sorted.
数组很大,我尽量避免在应用程序中对它们进行排序.
The arrays are pretty big and i try to avoid sort them in the the application.
Document Example :
{
"_id" : ObjectId("52a84825cc8391ab188b4567"),
"id" : 129624
"message" : "Sample",
"date" : "12-09-2013,17:34:34",
"dt" : ISODate("2013-12-09T17:34:34.000Z"),
}
查询:
db.uEvents.aggregate(
[
{$match : {dt : {$gte : new Date(2014,01,01) , $lt : new Date(2015,01,17)}}}
,{$sort : {dt : 1}}
, {$group : {
_id : {
id : "$id"
, year : {'$year' : "$dt"}
, month : {'$month' : "$dt"}
, day : {'$dayOfMonth' : "$dt"}
}
,dt : {$addToSet : "$dt"}
}}
]
);
推荐答案
是可以的,但是使用不同的方法.我只是为此提供自己的数据,但是您会明白的.
Yes it is possible, but approach it differently. I'm just provide my own data for this, but you'll get the concept.
我的样本:
{ "array" : [ 2, 4, 3, 5, 2, 6, 8, 1, 2, 1, 3, 5, 9, 5 ] }
我要对此CTO进行半报价",并声明集合被认为是无序.
I'm going to "semi-quote" the CTO on this and state that Sets are considered to be unordered.
Google组有一个实际的JIRA声明,类似这样.因此,让我们从"Elliot"中获取它,并接受这种情况 .
因此,如果要获得有序的结果,则必须在这样的阶段进行按摩
So if you want an ordered result, you have to massage that way with stages like this
db.collection.aggregate([
// Initial unwind
{"$unwind": "$array"},
// Do your $addToSet part
{"$group": {"_id": null, "array": {"$addToSet": "$array" }}},
// Unwind it again
{"$unwind": "$array"},
// Sort how you want to
{"$sort": { "array": 1} },
// Use $push for a regular array
{"$group": { "_id": null, "array": {"$push": "$array" }}}
])
然后执行任何操作.但是现在您的数组已排序.
And then do whatever. But now your array is sorted.
这篇关于排序聚合addToSet结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!