【问题标题】:Sorting aggregation addToSet result排序聚合 addToSet 结果
【发布时间】:2014-03-24 21:41:36
【问题描述】:

有没有办法将 $addToSet 的结果作为排序数组?

我尝试扩展管道并 $unwind 数组,对其进行排序并再次分组, 但结果仍然没有排序。

数组非常大,我尽量避免在应用程序中对它们进行排序。

文档示例: { "_id" : ObjectId("52a84825cc8391ab188b4567"), “身份证”:129624 “消息”:“样本”, “日期”:“2013 年 12 月 9 日,17:34:34”, “dt”:ISODate(“2013-12-09T17:34:34.000Z”), }

查询:

db.uEvents.aggregate( [ {$match:{dt:{$gte:新日期(2014,01,01),$lt:新日期(2015,01,17)}}} ,{$sort : {dt : 1}} ,{$组:{ _ID : { id : "$id" , 年 : {'$year' : "$dt"} , 月 : {'$month' : "$dt"} , 日: {'$dayOfMonth': "$dt"} } ,dt : {$addToSet : "$dt"} }} ] );

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    是的,这是可能的,但方法不同。我只是为此提供我自己的数据,但你会明白这个概念。

    我的样本:

    { "array" : [  2,  4,  3,  5,  2,  6,  8,  1,  2,  1,  3,  5,  9,  5 ] }
    

    我将就此“半引用”CTO 并声明 Sets 被认为是无序

    有一个实际的 JIRA,Google groups 声明是这样的。因此,让我们从“Elliot”中理解并接受这是这样的。

    所以如果你想要一个有序的结果,你必须用这样的阶段来按摩

    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" }}}
    
    ])
    

    然后做任何事情。但是现在您的数组已排序。

    【讨论】:

    • 这是正确的!但奇怪的是,当我在最后阶段使用 $addToSet 而不是 $push 时,它没有被订购。
    • @alon_r 这一点都不奇怪。 特别是,因为我引用了 MongoDB 的 CTO 的话。 “集合被认为是无序的”。仅供参考,“Elliot”还使 sets 可能最终被视为其 自己的 数据类型的 cmets,与数组分开。因此需要re-cast区分。当你得到一些代表时投票。很多知识都是免费的。
    猜你喜欢
    • 1970-01-01
    • 2014-12-24
    • 1970-01-01
    • 2021-06-01
    • 2019-01-14
    • 1970-01-01
    • 2015-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多