使用 Mongoose.js 按嵌套数组中的字段排序

2024-01-29

考虑到下面的数据结构(基于我的模型),我将如何使用猫鼬按 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 ...)

有没有更好或更有效的方法来做到这一点?

在此先感谢您的帮助。


您正在寻找的是按数组中的字段排序时的标准行为。

MyModel.find().sort('-cars.year').exec(function(err, docs) {...});

这将使用最大值对文档进行降序排序year的元素中cars来自每个文档。

当升序排序时,使用最小值。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Mongoose.js 按嵌套数组中的字段排序 的相关文章

随机推荐