[英]How to merge two arrays of objects by the same field using MongoDB aggregation?
[英]How can I merge two objects with aggregation in mongodb,?
我在合並對象時遇到問題,我有一個工廠架構,其中包含一個汽車屬性,其中包含每輛車的引用,我想將工廠與最后注冊的汽車合並。 我有以下數據。
"Factory": {
_id: ""
"factories" : [
{
"Adress" : "...",
"name": "Factory A"
"car": [ ObjectId("5f974ac1200b1aa93fee248b") ]
},
{
"Adress" : "...",
"name": "Factory B"
"car": [ ObjectId("5f974ac1200b1aa93fee248b") ]
}
],
},
汽車收藏:
"Car" :
_id: ObjectId("5f974ac1200b1aa93fee248b")
"color" : "...",
"feature": "..."
},
我期望的輸出:
[
{
"Factory A": {
"Adress" : "...",
"name": "Factory A"
"cars": {
_id: ObjectId("5f974ac1200b1aa93fee248b")
"color" : "...",
"feature": "..."
}
},
"Factory B": {
"Adress" : "...",
"name": "Factory B"
"car": {
_id: ObjectId("5f974ac1200b1aa93fee248b")
"color" : "...",
"feature": "..."
}
},
}
]
我得到的輸出:
"Factory A": {
{
"Adress" : "...",
"name": "Factory A",
"car": [ ObjectId("5f974ac1200b1aa93fee248b") ]
},
"car": {
_id: ObjectId("5f974ac1200b1aa93fee248b")
"color" : "...",
"feature": "..."
}
}
"Factory B": {
{
"Adress" : "...",
"name": "Factory B",
"car": [ ObjectId("5f974ac1200b1aa93fee248b") ]
},
"car": {
_id: ObjectId("5f974ac1200b1aa93fee248b")
"color" : "...",
"feature": "..."
}
}
這是我的操作:
db.getCollection('factory').aggregate([
{ $match: { "_id": ObjectId("5f9740f38591d84413600db0") } },
{ $unwind: "$factories"},
{ $group: { _id: null, allFactories: { $addToSet: "$factories"} } },
{ $unwind: "$allFactories" },
{
$lookup: {
from: "cars",
localField: "allFactories.car",
foreignField: "_id",
as: "cars"
}
},
{ $sort: { "cars._id": -1 } },
{ $unwind: "$cars" },
{ $group: {_id:"$allFactories.name", lastMatch: { $last: "$$ROOT"} }}
請問這種方法有什么幫助嗎?
你可以試試這個查詢。 您將不得不稍微調整一下 ObjectIds。 我使用了字符串,因為文檔在 mongo playground 中出錯。 但我認為那將是直截了當的。
db.factory.aggregate([
{
"$match": {
"_id": 1
}
},
{
$unwind: "$factories"
},
{
"$unwind": "$factories.car"
},
{
"$lookup": {
"from": "cars",
"localField": "factories.car",
"foreignField": "id",
"as": "factories.car"
}
},
{
"$unwind": "$factories.car"
},
{ "$group": {
"_id": null,
"data": {
"$push": {
"k": "$factories.name",
"v": "$factories"
}
}
}},
{ "$replaceRoot": {
"newRoot": { "$arrayToObject": "$data" }
}}
])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.