查询mongoose中的数组子文档
Querying array sub-document in mongoose
我在 Node.js
应用程序中使用 MongoDB mongoose
。
我的数据库中有一个集合,可以用以下模式描述:
{
id: String,
name: String,
indicators: [{
date: Date,
value: Number
}]
}
其中id
是唯一的,每个文档里面都有很多indicators
。
我希望能够根据indicators
数组的属性查询集合。例如:按日期对数组进行排序或限制数组中结果的数量(可能带有偏移量)。
我该怎么做?
您可以使用 $slice
限制数组中的项目数。例如:
Model.find({}, { indicators: { $slice: 5 } }, function(err, data) {
// ...
});
请问return前5个元素。
但是如果要排序,那就得用聚合框架了:
Model.aggregate([
{ $unwind: '$indicators' },
{ $sort: { 'indicators.date': -1 } }
], function(err, data) { /* .... */ });
我在 Node.js
应用程序中使用 MongoDB mongoose
。
我的数据库中有一个集合,可以用以下模式描述:
{
id: String,
name: String,
indicators: [{
date: Date,
value: Number
}]
}
其中id
是唯一的,每个文档里面都有很多indicators
。
我希望能够根据indicators
数组的属性查询集合。例如:按日期对数组进行排序或限制数组中结果的数量(可能带有偏移量)。
我该怎么做?
您可以使用 $slice
限制数组中的项目数。例如:
Model.find({}, { indicators: { $slice: 5 } }, function(err, data) {
// ...
});
请问return前5个元素。
但是如果要排序,那就得用聚合框架了:
Model.aggregate([
{ $unwind: '$indicators' },
{ $sort: { 'indicators.date': -1 } }
], function(err, data) { /* .... */ });