skip to Main Content

Hello how to change an id of document to diffrent when some ids are equal?
I want to change some of employees id_director to object id thats is equal to id_director. I mean for example, when some document have id_director = 100 then changed it to _id with value of employee where id_employee = 100.

I was trying like this:

var employes = db.employees.find({"id_director": {$ne: null}});
while (employes.hasNext()) {
emp = employes.next();
employe = db.employees.findOne({"id_director":emp.id_employe});


emp.id_director = employe._id

db.employees.save(emp)

}

For example

I have two documents in one collection:

employees
{
    "_id" : ObjectId("6224a5767b9cdbdcb681b1ef"),
    "id_employe" : 180,
    "id_director" : 100,
    "name" : "Mark"
}

{
    "_id" : ObjectId("6224a5767b9cdbdcb681b1f0"),
    "id_employe" : 100,
    "id_director" : null,
     "name" : "Peter"
}

Expected document:

{
    "_id" : ObjectId("6224a5767b9cdbdcb681b1ef"),
    "id_employe" : 180,
    "id_director" : ObjectId("6224a5767b9cdbdcb681b1f0"),
    "name" : "Mark"
}

2

Answers


  1. first of all you need to have peter’s id then update mark document:

    var peter= db.employees.findOne({_id: peterId});
    db.employees.updateOne({
        _id: markId
    }, {
        $set: {
            id_director: peter._id
        }
    })
    
    Login or Signup to reply.
  2. You can perform a self $lookup to lookup for the director_id, then perform some wrangling and $merge back to the collection.

    db.collection.aggregate([
      {
        "$match": {
          "id_director": {
            $ne: null
          }
        }
      },
      {
        "$lookup": {
          "from": "collection",
          "localField": "id_director",
          "foreignField": "id_employe",
          pipeline: [
            {
              "$limit": 1
            },
            {
              $project: {
                _id: 1
              }
            }
          ],
          "as": "id_director"
        }
      },
      {
        $unwind: "$id_director"
      },
      {
        $project: {
          _id: 1,
          id_employe: 1,
          id_director: "$id_director._id",
          name: 1
        }
      },
      {
        "$merge": {
          "into": "collection",
          "on": "_id",
          "whenMatched": "replace"
        }
      }
    ])
    

    Here is the Mongo playground for your reference.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search