Reputation: 3
I'm having trouble merging objects, I have a factory schema that contains a car property which has the refs of each car, I want to merge the factory with the last car registered. I have the following data.
"Factory": {
_id: ""
"factories" : [
{
"Adress" : "...",
"name": "Factory A"
"car": [ ObjectId("5f974ac1200b1aa93fee248b") ]
},
{
"Adress" : "...",
"name": "Factory B"
"car": [ ObjectId("5f974ac1200b1aa93fee248b") ]
}
],
},
Car collection:
"Car" :
_id: ObjectId("5f974ac1200b1aa93fee248b")
"color" : "...",
"feature": "..."
},
the output that I expect:
[
{
"Factory A": {
"Adress" : "...",
"name": "Factory A"
"cars": {
_id: ObjectId("5f974ac1200b1aa93fee248b")
"color" : "...",
"feature": "..."
}
},
"Factory B": {
"Adress" : "...",
"name": "Factory B"
"car": {
_id: ObjectId("5f974ac1200b1aa93fee248b")
"color" : "...",
"feature": "..."
}
},
}
]
the output that I get:
"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": "..."
}
}
This is my operation:
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"} }}
any help with this approach please?
Upvotes: 0
Views: 445
Reputation: 1625
You can try this query. You will have to tweak this a bit ObjectIds. I have used string as the document were giving error in mongo playground. But i think that would be straight forward.
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" }
}}
])
Upvotes: 1