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
first of all you need to have peter’s id then update mark document:
You can perform a self
$lookup
to lookup for the director_id, then perform some wrangling and$merge
back to the collection.Here is the Mongo playground for your reference.