【问题标题】:How can I populate nested array objects in mongoDB or mongoose?如何在 mongoDB 或 mongoose 中填充嵌套数组对象?
【发布时间】:2022-11-10 01:17:45
【问题描述】:
我有一个 orders 集合,其中每个 order 具有以下形状:
{
"_id": "5252875356f64d6d28000001",
"lineItems": [
{ productId: 'prod_007', quantity: 3 },
{ productId: 'prod_003', quantity: 2 }
]
// other fields omitted
}
我还有一个products 集合,其中每个product 都包含一个唯一的productId 字段。
如何使用来自products 集合的匹配product 填充每个lineItem.productId?谢谢! :)
【问题讨论】:
标签:
mongodb
mongoose
aggregation-framework
【解决方案1】:
我不知道您想要的确切输出,但我认为这就是您要寻找的:
这里的技巧是在聚合阶段使用$lookup。
- 首先
$unwind 解构数组并可以将每个id 与另一个集合合并。
- 然后是
$lookup 本身。这就像 SQL 中的联接。它合并具有相同 ID 的所需对象。
- 然后使用
$mergeObjects 重新创建种群以从两个集合中获取属性。
- 最后重新组合对象以再次获取数组。
db.orders.aggregate([
{
"$unwind": "$lineItems"
},
{
"$lookup": {
"from": "products",
"localField": "lineItems.productId",
"foreignField": "_id",
"as": "result"
}
},
{
"$set": {
"lineItems": {
"$mergeObjects": [
"$lineItems",
{
"$first": "$result"
}
]
}
}
},
{
"$group": {
"_id": "$_id",
"lineItems": {
"$push": "$lineItems"
}
}
}
])
示例here
使用此查询,您拥有相同的初始数据,但“填充”了来自其他集合的值。