排序字段与Mongoose.js嵌套数组 [英] Sort by field in nested array with Mongoose.js

查看:807
本文介绍了排序字段与Mongoose.js嵌套数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面给出我将如何去有关cars.year的倒序与猫鼬整理收集的数据结构(基于我的模型)?所以,首先我觉得汽车数组中的最大一年,然后由排序集合。

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?

在此先感谢您的帮助。

推荐答案

您要寻找的是标准的行为,由现场的数组排序时。

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.

这篇关于排序字段与Mongoose.js嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆