【发布时间】:2018-08-13 16:24:54
【问题描述】:
所以对于我的示例数据库设置:
db.lists.insertMany([
{ _id: "1", name: "list1", included_lists: ["2"], items: ["i1"] },
{ _id: "2", name: "list2", included_lists: [], items: ["i2", "i3"] }
])
db.items.insertMany([
{ _id: "i1", name: "item1", details: [{}, {}, {}] },
{ _id: "i2", name: "item2", details: [{}, {}, {}] },
{ _id: "i3", name: "item3", details: [{}, {}, {}] }
])
我目前正在通过以下方式获取我的商品数据:
db.lists.aggregate([
{ "$match": { "_id": { "$in": ["1", "2"] } } },
{
"$lookup": {
"from": "items",
"localField": "items",
"foreignField": "_id",
"as": "item"
}
},
{ "$unwind": "$item" },
{
"$facet": {
"results": [
{ "$skip": 0 },
{ "$limit": 10 },
{
"$project": {
name: 1,
item: 1
}
}
],
"total": [
{ "$count": "total" },
]
}
}
]).pretty()
返回:
{
"results" : [
{
"_id" : "1",
"name" : "list1",
"item" : {
"_id" : "i1",
"name" : "item1",
"details" : [
{
},
{
},
{
}
]
}
},
{
"_id" : "2",
"name" : "list2",
"item" : {
"_id" : "i2",
"name" : "item2",
"details" : [
{
},
{
},
{
}
]
}
},
{
"_id" : "2",
"name" : "list2",
"item" : {
"_id" : "i3",
"name" : "item3",
"details" : [
{
},
{
},
{
}
]
}
}
],
"total" : [
{
"total" : 3
}
]
}
我想要做的是删除{ "$match": { "_id": { "$in": ["1", "2"] } } },,因为我想删除获取id数组所需的查询,而是从列表_id及其included_lists ids中获取所有id .然后像我的结果一样返回所有items 返回。
这个问题类似于:mongodb - unwinding nested subdocuments,但由于模棱两可和缺少 db 文档,我再次提出。
【问题讨论】:
-
如果要遍历所有列表文档,为什么还需要包含列表?听起来你只是不喜欢匹配声明
-
@AmitWagner 我不想遍历列表文件。我只想要
_id所需列表中的内容以及included_lists中的任何内容。因此,如果我要定位列表"2",我最多只会返回 2 个结果。 -
你也可以发布预期的输出
标签: javascript mongodb mongoose