Consider the current collection:
# the manager
db.employees.insert({_id: ObjectId(
"4d85c7039ab0fd70a117d730"),
name: 'Leto'})
# the yours employees
db.employees.insert({_id: ObjectId(
"4d85c7039ab0fd70a117d731"),
name: 'Duncan',
manager: ObjectId(
"4d85c7039ab0fd70a117d730")});
db.employees.insert({_id: ObjectId(
"4d85c7039ab0fd70a117d732"),
name: 'Moneo',
manager: ObjectId(
"4d85c7039ab0fd70a117d730")});
With this model, Is possible recover the employees
with the manager
field with the literal Leto
document? Something like
{ "_id" : ObjectId("4d85c7039ab0fd70a117d730"), "name" : "Leto" }
{ "_id" : ObjectId("4d85c7039ab0fd70a117d731"), "name" : "Duncan", "manager" : { "_id" : ObjectId("4d85c7039ab0fd70a117d730"), "name" : "Leto" } }
{ "_id" : ObjectId("4d85c7039ab0fd70a117d732"), "name" : "Moneo", "manager" : { "_id" : ObjectId("4d85c7039ab0fd70a117d730"), "name" : "Leto" } }
Rather than
{ "_id" : ObjectId("4d85c7039ab0fd70a117d730"), "name" : "Leto" }
{ "_id" : ObjectId("4d85c7039ab0fd70a117d731"), "name" : "Duncan", "manager" : ObjectId("4d85c7039ab0fd70a117d730") }
{ "_id" : ObjectId("4d85c7039ab0fd70a117d732"), "name" : "Moneo", "manager" : ObjectId("4d85c7039ab0fd70a117d730") }
If not, how i can do it? Because i am worried in literally put the manager inside the manager
field because this will be complex to update in the future
Thank you very much.
Try using the
forEach()
method of thefind()
cursor to iterate over documents that have the manager key (through the$exists
operator and the$type
operator to check if it's anObjectId
) and within each loop you query the collection for the manager document withfindOne()
and assign it as a subdocument for themanager
property:Result: