【发布时间】:2020-12-05 03:59:57
【问题描述】:
我在 MongoDB 中有以下集合
个人资料集合
> db.Profile.find()
{ "_id" : ObjectId("5ec62ccb8897af3841a46d46"), "u" : "Test User", "is_del": false }
商店收藏
> db.Store.find()
{ "_id" : ObjectId("5eaa939aa709c30ff4703ffd"), "id" : "5ec62ccb8897af3841a46d46", "a" : { "ci": "Test City", "st": "Test State" }, "ip" : false }, "op" : [ ], "b" : [ "normal" ], "is_del": false}
物品收藏
> db.Item.find()
{ "_id" : ObjectId("5ea98a25f1246b53a46b9e10"), "sid" : "5eaa939aa709c30ff4703ffd", "n" : "sample", "is_del": false}
这些集合之间的关系定义如下:
-
Profile -> Store:是1:n关系。Store中的id字段与Profile中的_id字段相关。 -
Store->Item:也是1:n关系。Item中的sid字段与Store中的_id字段相关。
我有一个查询要查找所有配置文件商店以及每个商店的Item 计数。查询如下(我从the answer得到的)
db.Profile.aggregate([
{
$match: { is_del: false }
},
{
$lookup: {
from: "Store",
as: "stores",
let: {
pid: { $toString: "$_id" }
},
pipeline: [
{
$match: {
is_del: false,
$expr: { $eq: ["$$pid", "$id"] }
}
},
{
$lookup: {
from: "Item",
as: "items",
let: {
sid: { $toString: "$_id" }
},
pipeline: [
{
$match: {
is_del: false,
$expr: { $eq: ["$$sid", "$sid"] }
}
},
{
$count: "count"
}
]
}
},
{
$unwind: "$items"
}
]
}
}
])
现在,我需要对结果进行分页。如何在汇总结果中分页?什么是可扩展的方法?
【问题讨论】:
标签: mongodb mongodb-query