gpt4 book ai didi

javascript - mongodb - 汇总和展开外国引用文件

转载 作者:行者123 更新时间:2023-11-30 20:17:12 24 4
gpt4 key购买 nike

因此对于我的示例数据库设置:

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 id 中获取所有 id。然后像我的结果一样返回所有 items

这个问题类似于:mongodb - unwinding nested subdocuments但由于歧义和缺少数据库文件,我已经重新询问了。

最佳答案

你可以通过图形查找然后分组来做到这一点

db.lists.aggregate([
{ "$match": { "_id": { "$in": ["1"] } } },
{
$graphLookup: {
from: "lists",
startWith: "$_id" ,
connectFromField: "included_lists",
connectToField: "_id",
as: "connected",
}
},

{$unwind:"$connected"},
{ $group:{_id:"$connected._id",items:{$first:'$connected.items'},name:{$first:'$connected.name'}}},
{
"$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()

关于javascript - mongodb - 汇总和展开外国引用文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51816656/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com