MongoDB:对子文档中的数组进行排序并保持文档结构

时间:2019-06-20 15:11:18

标签: mongodb

我的文档结构如下:

_id: 5d090529397f79d2fefc57fb,    
result: 23232,
length: 32323,
position: 34343,
temperatures: { 
    temp_limits: { 
        min: 10,
        max: 31,            
    },
    temp_cities:
        [ 
            { 
                city: 'city_1',
                city_temp: { temp: 21, date: 2018-12-18T10:35:07.000Z},
                locked: false
            },
            { 
                city: 'city_2',
                city_temp: { temp: 17, date: 2018-12-19T10:35:07.000Z},
                locked: true
            },
            { 
                city: 'city_4',
                city_temp: { temp: 25, date: 2018-12-21T10:35:07.000Z},
                locked: false
            },

    ]
}

我需要按temp_cities值对子文档temperatures中的数组temp进行排序。我需要这个结果:

_id: 5d090529397f79d2fefc57fb,    
result: 23232,
length: 32323,
position: 34343,
temperatures: { 
    temp_limits: { 
       min: 10,
       max: 31,            
    },
    temp_cities:
       [ 
            { 
                city: 'city_2',
                city_temp: { temp: 17, date: 2018-12-19T10:35:07.000Z},
                locked: true
            },
            { 
                city: 'city_1',
                city_temp: { temp: 21, date: 2018-12-18T10:35:07.000Z},
                locked: false
            },

            { 
                city: 'city_4',
                city_temp: { temp: 25, date: 2018-12-21T10:35:07.000Z},
                locked: false
            },

     ]
}

我知道先用unwind然后用sort然后用group可以做什么。但是我发现这是一种非常精致的方法,因为我必须复制结构的其余部分。

类似这样的东西:

Model.aggregate([
  { $unwind: '$temperatures.temp_cities'},   
  { $sort: { 'temperatures.temp_cities.city_temp.temp': 1 } },
  { 
     $group: {
     _id: {
       _id: '$_id',           
     },                
     result: { $first: '$result' },
     position: { $first: '$position' },
     [...] // replicate all elements        
   }
 }
])

有更好的方法吗?

0 个答案:

没有答案