【发布时间】:2018-12-11 02:58:02
【问题描述】:
我正在尝试对嵌套的子文档进行排序和限制,在查找并尝试了不同的解决方案之后,我就是想不通。
系统
const systemSchema = mongoose.Schema({
data: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Data'
}],
...other
})
数据
const dataSchema = mongoose.Schema({
measurements: [measurementSchema]
...other
})
测量
const measurementSchema = mongoose.Schema({
date: {
type: Date,
required: true
},
...other
}, { _id : true })
如上所示; 1 个系统 -> 数据数组 -> 测量数组
我想按日期和限制订购测量值。
我的尝试
我尝试的第一件事是使用填充选项,如下所示:
return System
.find({ _id: { $in: systemIds } })
.populate({
path: 'data',
populate: {
path: 'measurements',
options: {
sort: { date: 1 }, // <-- doesn't work
limit: 5 // <-- does work
}
}
})
这样尝试确实会限制测量数组,但不会对其进行排序。
在那之后,我尝试使用聚合并尝试了很多代码,但没有一个可以工作,所以我将它们排除在帖子之外。
使用 mongoDB 3.4.7
样本数据
{
"systems": [
{
"data": [
{
"_id": "5c0d87f77f93b06476be9cfd",
"measurements": [
{
"_id": "5c0d894178fc6c64cd36ffeb",
"value": "17",
"date": "2018-12-09T21:29:37.662Z"
}
{
"_id": "5c0d8952e418d464d6268bfc",
"value": "23",
"date": "2018-12-09T21:29:54.354Z"
},
{
"_id": "5c0d894b78fc6c64cd36fffb",
"value": "34",
"date": "2018-12-09T21:29:47.770Z"
},
{
"_id": "5c0d89503de6d564d2d32385",
"value": "19",
"date": "2018-12-09T21:29:52.293Z"
},
{
"_id": "5c0d894678fc6c64cd36fff3",
"value": "16",
"date": "2018-12-09T21:29:42.766Z"
},
]
}
],
"_id": "5c0d87f77f93b06476be9d01"
}
]
}
【问题讨论】:
-
能否将您的 mongodb 版本更新到 3.6 或更高版本?