繁体   English   中英

在猫鼬中查询数组子文档

[英]Querying array sub-document in mongoose

我在使用MongoDB中Node.js与App mongoose 我的数据库中有一个集合,可以用以下模式描述:

{
  id: String,
  name: String,
  indicators: [{
    date: Date,
    value: Number
  }]
}

id是唯一的,并且每个文档中都有很多indicators

我希望能够根据indicators数组的属性查询集合。 例如:按日期对数组排序或限制数组中的结果数量(可能带有偏移量)。

我怎样才能做到这一点?

您可以使用$slice限制数组中的项目数。 例如:

Model.find({}, { indicators: { $slice: 5 } }, function(err, data) {
    // ...
});

将返回前5个元素。

但是,如果要对其进行排序,则必须使用聚合框架:

Model.aggregate([
    { $unwind: '$indicators' },
    { $sort: { 'indicators.date': -1 } }
], function(err, data) { /* .... */ });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM