简体   繁体   English

如何对内部数组元素进行排序,同时保持对外部文档的不同排序?

[英]How to sort inner array elements while maintaining different sorting for outer documents?

I have a collection of documents each of which has an embedded array. 我有一组文档,每个文档都有一个嵌入式数组。 I need the elements of each array to be sorted within themselves, while the containing documents should remain ordered as they are. 我需要每个数组的元素在它们内部进行排序,而包含的文档应保持原样。

As an exemplification, taking the data from this similar question on sorting: 作为一个示例,从类似的排序问题中获取数据:

[
    {
        name: 'item1',
        slots: [
            { date : ISODate("2013-01-18T23:00:00Z") },
            { date : ISODate("2013-02-05T23:00:00Z") },
            { date : ISODate("2013-03-24T23:00:00Z") },
        ]
    },
    {
        name: 'item2',
        slots: [
            { date : ISODate("2013-01-12T23:00:00Z") },
            { date : ISODate("2013-01-03T23:00:00Z") },
            { date : ISODate("2013-03-04T23:00:00Z") },
        ]
    },
    {
        name: 'item3',
        slots: [
            { date : ISODate("2013-03-14T23:00:00Z") },
            { date : ISODate("2013-02-18T23:00:00Z") },
            { date : ISODate("2013-03-07T23:00:00Z") },
        ]
    }
]

My expected result is slightly different: 我的预期结果略有不同:

[
    {
        name: 'item3',
        slots: [
            { date : ISODate("2013-02-18T23:00:00Z") },
            { date : ISODate("2013-03-07T23:00:00Z") },
            { date : ISODate("2013-03-14T23:00:00Z") },
        ]
    },
    {
        name: 'item2',
        slots: [
            { date : ISODate("2013-01-03T23:00:00Z") },
            { date : ISODate("2013-01-12T23:00:00Z") },
            { date : ISODate("2013-03-04T23:00:00Z") },
        ]
    },
    {
        name: 'item1',
        slots: [
            { date : ISODate("2013-01-18T23:00:00Z") },
            { date : ISODate("2013-02-05T23:00:00Z") },
            { date : ISODate("2013-03-24T23:00:00Z") },
        ]
    }
]

How can I achieve this in MongoDB 3.6? 如何在MongoDB 3.6中实现呢? I'd like to use the aggregation pipeline, if possible. 如果可能的话,我想使用聚合管道。

I didn't try much so far, since the only stage I can think would fit for this is the $sort , but as stated in the documentation , it will sort the outer collection. 到目前为止,我还没有做太多尝试,因为我认为唯一适合该步骤的阶段是$sort ,但是正如文档中所述 ,它将对外部集合进行排序。

You can use the below aggregation query. 您可以使用以下聚合查询。

$unwind the slots array followed by sorting the docs date asc and $group back on _id to get the sorted array. $unwind the slots数组,然后将文档日期asc和$group重新排序到_id以获取排序后的数组。

$sort on name desc to sort the documents. $sort desc name上的$sort对文档进行排序。

db.col.aggregate([
  {"$unwind":"$slots"},
  {"$sort":{"slots.date":1}},
  {"$group":{"_id":"$_id","name":{"$first":"$name"},"slots":{"$push":"$slots"}}},
  {"$sort":{"name":-1}},
])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM