【问题标题】:Sort by field in nested array with Mongoose.js使用 Mongoose.js 按嵌套数组中的字段排序
【发布时间】:2015-03-15 14:46:39
【问题描述】:

鉴于下面的数据结构(基于我的模型),我将如何使用 mongoose 按cars.year 按 desc 顺序对集合进行排序?所以首先我在汽车数组中找到最大年份,然后按此对集合进行排序。

{ "_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 为汽车数组中的每个元素复制了我的结果。

MyModel
    .aggregate([{
        $unwind: "$cars"
    }, {
        $project: {
            ...
            year: '$cars.year',
        }
    }, {
        $sort: {
            year: -1
        }
    }])
    .exec(function ...)

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

提前感谢您的帮助。

【问题讨论】:

    标签: javascript arrays node.js mongodb mongoose


    【解决方案1】:

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

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

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

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

    【讨论】:

    • @AryehArmon 有什么不适合你的?请记住,它对文档进行排序,而不是每个文档中的 cars 数组。
    猜你喜欢
    • 2021-08-07
    • 2018-09-13
    • 1970-01-01
    • 2013-05-03
    • 2017-12-31
    • 2018-10-22
    • 2019-10-25
    • 2015-10-24
    • 1970-01-01
    相关资源
    最近更新 更多