'Update id in mongodb collection
Hello im learning MongoDB and my exercise is to update id in one of my collection to another id. I Have two collection
First collection "workers" :
{
"_id" : ObjectId("6224ec342c2d7202b9ad9af6"),
"id_worker" : 180,
"id_boss" : 100,
"hired" : ISODate("2005-02-20T00:00:00Z"),
"id_group" : 10
}
Second collection "groups":
{
"_id" : ObjectId("6224ebe12c2d7202b9ad9af1"),
"id_group" : 10,
"name" : "Administrators",
"addres" : "Example"
}
I would like to change an "_id" of my worker to its "identifiaction id" from collection "groups"
So my worker should look like:
{
"_id" : ObjectId("6224ec342c2d7202b9ad9af6"),
"id_worker" : 180,
"id_boss" : 100,
"hired" : ISODate("2005-02-20T00:00:00Z"),
"id_group" : ObjectId("6224ebe12c2d7202b9ad9af1")
}
I have query like this. When i use print it shows list of my workers with name of the group. How to change it to modify this collection? use update?
var workers = db.workers.find();
while (workers.hasNext()) {
worker = workers.next();
group = db.groups.findOne({"id_group": worker.id_group});
print(group.name);
}
Solution 1:[1]
Try this:
db.workers.aggregate([
{
$lookup: {
from: "groups",
localField: "id_group",
foreignField: "id_group",
as: "group"
}
},
{
$project: {
id_worker: 1,
id_boss: 1,
hired: 1,
id_group: { $first: "$group.name" }
}
}
])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Wernfried Domscheit |