我的文档结构如下:
_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
}
}
])
有更好的方法吗?