Sort by field in nested array with Mongoose.js

久未见 提交于 2021-01-27 13:10:25

问题


Given the data structure (based on my model) below how would I go about sorting the collection by cars.year in desc order with mongoose? So that first I find the max year in the cars array and then sort the collection by that.

{ "_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",}
  ]
}

I tried something like this with the aggregation function, but $unwind duplicates my results for each element in the cars array.

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

Is there a better or more efficient way to go about doing this?

Thanks in advance for your help.


回答1:


What you're looking for is the standard behavior when sorting by a field in an array.

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

This will sort the docs descending using the maximum value of year in the elements of cars from each doc.

When sorting ascending, the minimum value is used.



来源:https://stackoverflow.com/questions/27993410/sort-by-field-in-nested-array-with-mongoose-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!