MongoDb如何将文档的id更改为不同的
您好,当某些ID相等时,如何将文档ID更改为Diffent? 我想将一些员工更改为id_director
到对象ID等于id_director
。我的意思是,例如,当某些文档具有id_director = 100
时,然后将其更改为_id,其中id_employeee = 100
。
我当时尝试过这样的尝试:
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)
}
例如,
我在一个集合中有两个文档:
employees
{
"_id" : ObjectId("6224a5767b9cdbdcb681b1ef"),
"id_employe" : 180,
"id_director" : 100,
"name" : "Mark"
}
{
"_id" : ObjectId("6224a5767b9cdbdcb681b1f0"),
"id_employe" : 100,
"id_director" : null,
"name" : "Peter"
}
预期文档:
{
"_id" : ObjectId("6224a5767b9cdbdcb681b1ef"),
"id_employe" : 180,
"id_director" : ObjectId("6224a5767b9cdbdcb681b1f0"),
"name" : "Mark"
}
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"
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先你需要有 Peter 的 id 然后更新标记文档:
first of all you need to have peter's id then update mark document:
您可以执行一个自我
$查找
以查找导演,然后执行一些争吵,$ MERGE
返回集合。这是 mongo playground 供您参考。
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.