假设我有一个collectionorders
:
[
{
"id":"1",
"items":{
"itemId":"1000",
"name":"Item 1",
"status":"STATUS"
}
},
{
"id":"2",
"items":{
"itemId":"1000",
"name":"Item 1",
"status":"ANOTHER_STATUS"
}
}
]
我有另一个集合item_projections
它是
[
{
"id":"1",
"itemId":"1000",
"name":"Item 1",
"orderId":"1"
},
{
"id":"1",
"itemId":"1000",
"name":"Item 1",
"orderId":"2"
}
]
对于集合orders
中的每个项目,我想将字段status
复制到投影中,并匹配顺序id
和itemId
,以具有
[
{
"id":"1",
"itemId":"1000",
"name":"Item 1",
"orderId":"1",
"status":"STATUS"
},
{
"id":"1",
"itemId":"1000",
"name":"Item 1",
"orderId":"2",
"status":"ANOTHER_STATUS"
}
]
有可能用聚合查找和合并管道来做吗?
解决方案1
-
$lookup
-item_projections
collection (key:orderId
)连接orders
collection (key:id
),返回orders
数组字段,仅包含status
字段的文档。 -
$replaceRoot
-用新文档替换输入文档。2.1。
$mergeObjects
-将根文档与orders
的第一个文档合并。 -
$unset
-删除orders
字段。
db.item_projections.aggregate([
{
"$lookup": {
"from": "orders",
"localField": "orderId",
"foreignField": "id",
"pipeline": [
{
$project: {
status: "$items.status"
}
}
],
"as": "orders"
}
},
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
"$$ROOT",
{
$first: "$orders"
}
]
}
}
},
{
$unset: "orders"
}
])
Sample Mongo Playground (Solution 1)
解决方案2
或者你可以用$project
代替第二和第三级。
{
$project: {
"id": 1,
"itemId": 1,
"name": 1,
"orderId": 1,
"status": {
$first: "$orders.status"
}
}
}
Sample Mongo Playground (Solution 2)