【发布时间】:2021-12-07 00:36:12
【问题描述】:
我正在开发一个带有Express 的nodeJS 服务,它使用MongoDB 作为数据库,并且我有包含嵌套对象的文档。
我想要限制和分页聚合嵌套列表。
我的文件格式如下:
{
"_id": "61ae0f28131a77c9d5bbf242",
"time": 137537200058,
"description": "fake logs",
"data": "fake data",
"device": {
"model": "iPhone"
}
}
这是 mongo 查询
const db = request.client.db( DATABASE_NAME );
db.collection( COLLECTION_NAME )
.aggregate([
{ $group : { _id : "$device.model", logs: { $push: "$$ROOT" } } } ,
{ $sort: { _id: 1 } },
])
.skip( 5 )
.limit( 2 ) // <--------------- limit only aggregation
.toArray()
.then( docs => {
response.send({
status: STATUS_SUCCESS,
data: docs
});
})
;
limit() 在我的查询中,只限制根,但嵌套对象没有限制
查询结果示例
{
"_id": "Android",
"logs": [
{
"_id": "61ae0f28131a77c9d5bbf22f",
"time": 1231146117734,
"description": "fake logs",
"data": "fake data",
"device": {
"model": "Android"
}
},
... // <-------------- no-limits
]
},
{
"_id": "iPhone",
"logs": [
{
"_id": "...",
"time": 1231146117734,
"description": "fake logs",
"data": "fake data",
"device": {
"model": "iPhone"
}
},
... // <-------------- no-limits
]
}
【问题讨论】:
标签: node.js mongodb express aggregation-framework