Node.js 在mongodb中进行聚合查找后,如何填充深度嵌套的ID数组?
这个问题是问题的延伸 我在集合A、B和C中有以下文档Node.js 在mongodb中进行聚合查找后,如何填充深度嵌套的ID数组?,node.js,mongodb,mongoose,mongodb-query,aggregation-framework,Node.js,Mongodb,Mongoose,Mongodb Query,Aggregation Framework,这个问题是问题的延伸 我在集合A、B和C中有以下文档 "A": {_id: "A_id1", labelA: "LabelA1"}, {_id: "A_id2", labelA: "LabelA2"} "C": { _id: "C_id1", labelC: "LabelC1"}, {
"A":
{_id: "A_id1", labelA: "LabelA1"},
{_id: "A_id2", labelA: "LabelA2"}
"C":
{ _id: "C_id1", labelC: "LabelC1"},
{ _id: "C_id2",labelC: "LabelC2"}
"B":
{
_id: "B_id1",
labelB: "LabelB1",
refToA: "A_id1",
items: [
{
itemLabel: "a",
options: [ { optionLabel: "opt1", codes: [ "C_id1"] },
{ optionLabel: "opt2", codes: [ "C_id2"] } ]
}
]
},
{
_id: "B_id4",
labelB: "LabelB4",
refToA: "A_id2",
items: [
{ itemLabel: "b",
options: [ { optionLabel: "opt3", codes: [ "C_id1", "C_id2"]
}
]
}
集合B在字段“items”中嵌套了子文档数组,进一步将子文档数组嵌套为“items.options”。最后,第三个子级别“items.options.code”包含文档C的ID列表
我希望聚合A以收集引用A的所有B。我使用以下命令执行此操作:
db.A.aggregate([
{
$match: {
_id: "A_id1"
}
},
{
$lookup: {
from: "B",
let: {
refToA: "$_id"
},
pipeline: [
{
$match: { $expr: { $eq: ["$refToA", "$$refToA"]}}
},
],
as: "BCollection"
}
}
])
它给出了以下结果
{
"BCollection": [
{
"_id": "B_id1",
"items": [
{
"itemLabel": "a",
"options": [
{
"codes": [ "C_id1" ],
"optionLabel": "opt1"
},
{
"codes": [ "C_id2"],
"optionLabel": "opt2"
}
]
}
],
"labelB": "LabelB1",
"refToA": "A_id1"
}
],
"_id": "A_id1",
"labelA": "LabelA1"
}
现在,我想保留上述结构,并用集合C中的详细信息填充字段“codes”
{
"BCollection": [
{
"_id": "B_id1",
"items": [
{
"itemLabel": "a",
"options": [
{
"codes": [ { _id: "C_id1", labelC: "LabelC1"} ],
"optionLabel": "opt1"
},
{
"codes": [ { _id: "C_id2", labelC: "LabelC2"}],
"optionLabel": "opt2"
}
]
}
],
"labelB": "LabelB1",
"refToA": "A_id1"
}
],
"_id": "A_id1",
"labelA": "LabelA1"
}
我尝试了以下查询,但未产生所需的结果:
db.A.aggregate([
{
$match: {
_id: "A_id1"
}
},
{
$lookup: {
from: "B",
let: {
refToA: "$_id"
},
pipeline: [
{
$match: {
$expr: {
$eq: [
"$refToA",
"$$refToA"
]
}
}
},
{
$lookup: {
from: "C",
localField: "items.options.codes",
foreignField: "_id",
as: "items.option.codes"
}
}
],
as: "BCollection"
}
}
])
您可以在此处看到上述查询的输出:尝试以下操作:
db.A.aggregate([
{
$lookup:{
从:“B”,
let:{refToA:$\u id},
管道:[
{
$match:{
$expr:{$eq:[“$refToA”,“$$refToA”]}
}
},
{$unwind:“$items”},
{$unwind:“$items.options”},
{
$lookup:{
从:“C”,
localField:“items.options.code”,
foreignField:“\u id”,
as:“项目.选项.代码”
}
},
{
$group:{
_身份证:{
id:“$\u id”,
itemLabel:“$items.itemLabel”
},
labelB:{$first:$labelB},
refToA:{$first:$refToA},
项目:{
$push:{
“itemLabel”:“$items.itemLabel”,
“选项”:“$items.options”
}
}
}
},
{
$group:{
_id:“$\u id.id”,
labelB:{$first:$labelB},
refToA:{$first:$refToA},
项目:{
$push:{
itemLabel:“$\u id.itemLabel”,
“选项”:“$items.options”
}
}
}
}
],
as:“B收集”
}
}
]);
谢谢。我有一个问题要解决。我不想触摸像itemLabel或labelB这样的字段。这是我设置的一个玩具示例。在我的实际系统中,有许多字段,如项目标签。我必须在“$group”操作中明确设置它们吗?items
数组是否可以包含多个项,或者如示例中所示始终包含一个项?它可以包含多个项。