I have a database with 3 collections. The first one has documents with some references to the other ones.
I need a query to populate the references on projects so requirements are loaded. I've managed to $lookup the requirements array, but I can't get it work on the optionals array, as it's a field inside an object of an array. Notice it's an object with a reference and an extra field that needs to be preserved.
db.projects.findOne({user: ObjectId("602acb4b839ec6001d3ef506")})
{
"_id" : ObjectId("6033cf8503ac5003f873cc9b"),
"date" : 1614008193362,
"requirements" : [
ObjectId("6032c1249588930368d7603c"),
ObjectId("6032c2dc9588930368d7603e")
],
"status" : "ACTIVE",
"hours" : 10,
"expire" : 1629560197,
"optionals" : [
{
"requirement" : ObjectId("602e3104dd86db01c89dd47e"),
"amount" : 10
},
{
"requirement" : ObjectId("603171e89588930368d76038"),
"amount" : 10
}
],
"user" : ObjectId("602acb4b839ec6001d3ef506"),
"__v" : 0
}
db.requirements.findOne()
{
"_id" : ObjectId("602da2bbdd86db01c89dd479"),
"date" : "1613602429148",
"status" : "ACTIVE",
"name" : "Test1",
"description" : "Test1 description",
"creator" : ObjectId("602acb4b839ec6001d3ef506"),
"__v" : 0
}
Here it's pointed to a solution based on $lookup, but I can't get it work: MongoDB aggregate field in array of objects
db.project.aggregate([
{
$match : {user: ObjectId($interesting_user)}
},
{
$lookup: {
from: "requirements",
localField: "requirements",
foreignField: "_id",
as: "requirements"
}
},
{
$lookup: {
from: "requirements",
localField: "optionals.requirement",
foreignField: "_id",
as: "optionals.requirement"
}
},
]).pretty()
I am missing something here? Browsing the MongoDb Doc gave me no solution