考虑到下面的数据结构(基于我的模型),我将如何使用猫鼬按 cars.year 按降序对集合进行排序?因此,首先我在 cars 数组中找到最大年份,然后按该年份对集合进行排序。
{ "_id" : 1234,
"dealershipName": "Eric’s Mongo Cars",
"cars": [
{"year": 2013,
"make": "10gen",
"model": "MongoCar",},
{"year": 1985,
"make": "DeLorean",
"model": "DMC-12",}
]
},
{ "_id" : 1235,
"dealershipName": "Eric’s Mongo Cars",
"cars": [
{"year": 2015,
"make": "10gen",
"model": "MongoCar",},
{"year": 12001,
"make": "DeLorean",
"model": "DMC-12",}
]
}
我尝试使用聚合函数进行类似的操作,但是$unwind
复制 cars 数组中每个元素的结果。
MyModel
.aggregate([{
$unwind: "$cars"
}, {
$project: {
...
year: '$cars.year',
}
}, {
$sort: {
year: -1
}
}])
.exec(function ...)
有没有更好或更有效的方法来做到这一点?
在此先感谢您的帮助。