Project a _id ref field as document

108 Views Asked by At

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.

1

There are 1 best solutions below

0
On

Try using the forEach() method of the find() cursor to iterate over documents that have the manager key (through the $exists operator and the $type operator to check if it's an ObjectId) and within each loop you query the collection for the manager document with findOne() and assign it as a subdocument for the manager property:

db.employees.find({"manager": {"$exists": true, "$type": 7}}).forEach(function (e){
    var manager = db.employees.findOne({"_id": e.manager});
    e.manager = manager;
    db.employees.save(e);
});

db.employees.find();

Result:

/* 0 */
{
    "_id" : ObjectId("4d85c7039ab0fd70a117d730"),
    "name" : "Leto"
}

/* 1 */
{
    "_id" : ObjectId("4d85c7039ab0fd70a117d731"),
    "name" : "Duncan",
    "manager" : {
        "_id" : ObjectId("4d85c7039ab0fd70a117d730"),
        "name" : "Leto"
    }
}

/* 2 */
{
    "_id" : ObjectId("4d85c7039ab0fd70a117d732"),
    "name" : "Moneo",
    "manager" : {
        "_id" : ObjectId("4d85c7039ab0fd70a117d730"),
        "name" : "Leto"
    }
}