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?