我有一个包含对象的集合,每个对象都包含多个array.例如:
assmemblies: {
mechanicalItems: [{
mechanicalId: <ObjectId that references the mechanicalitems collection>,
quantity: Number
}],
electricalItems: [{
mechanicalId: <ObjectId that references the mechanicalitems collection>
quantity: Number
}],
我正在try 执行一次查找,以将mechanicalitems
和electricalitems
中的所有字段都放入程序集集合中,但是很难使$lookup
工作.
当我试图展开和分组时,我丢失了另一个数组,或者它最终嵌套在另一个数组中的每个数组对象中.
我还try 直接投射回Quantity属性,但是我得到了一个包含所有数量的数组:
{
$lookup: {
from: "mechanicalitems",
let: {
mechanicalItem: "$mechanicalItems",
item: "$machanicalItems.mechanicalId",
},
pipeline: [
{
$match: {
$expr: {
$in: ["$_id", "$$item"],
},
},
},
{
$project: {
"quantity": "$$mechanicalItem.quantity" // <-- this gives an array of all the quantities
}
},
],
as: "mechanicalItems",
},
},
我试过其他几种 Select ,但都不能完全得到我想要的.
*编辑-预期输出
如果我的mechanicalItems
个域是:‘尺寸’、‘material ’、‘风格’,而我的electricalItems
个域是:‘当前’、‘评级’、‘绝缘’,那么我的预期输出是:
assemblies: {
mechanicalItems: [{
item: {
_id: <some ObjectId>
size: '12',
material: 'steel',
style: 'thick'
},
quantity: Number
}, ...
],
electricalItems: [{
item: {
_id: <some ObjectId>
current: '15',
rating: 'low voltage',
insulation: 'PVC'
},
quantity: Number
}, ...
]
}
我希望用MachicalItems集合中的实际对象替换mechanicalItemId
(并最终将该字段重命名为"Item",但稍后我可以用$addFields
或$project
来实现这一点).