[英]How to update a collection based on another collection in MongoDB?
Now I get two collections: coll01
and coll02
. 现在我得到两个集合: coll01
和coll02
。
And the structure of coll01 is like this: 而coll01的结构是这样的:
{
id: 01,
name: "xxx",
age: 30
}
and the structure of coll02 is like: 和coll02的结构如下:
{
id: 01,
name: "XYZ"
gender: "male"
}
The two id fields in the both collection are indices. 两个集合中的两个id字段都是索引。 And the numbers of documents in these two collections are same. 这两个集合中的文档数量是相同的。
And what I want to do in traditional SQL is : 我想在传统SQL中做的是:
update coll01, coll02
set coll01.name = coll02.name
where coll01.id = coll02.id
Mongodb is not relational database and doesn't support join's. Mongodb不是关系数据库,不支持join。 So, you should think a little, do you really need mongodb for your purposes? 所以,你应该想一想,你真的需要mongodb用于你的目的吗?
Solution for update: you can update each document from coll01
in loop: 更新解决方案:您可以循环更新coll01
中的每个文档:
db.coll01.find().forEach(function (doc1) {
var doc2 = db.coll02.findOne({ id: doc1.id }, { name: 1 });
if (doc2 != null) {
doc1.name = doc2.name;
db.coll01.save(doc1);
}
});
Index for id
field in coll02
collection will decrease find()
operation execution time inside the loop. coll02
集合中id
字段的索引将减少循环内的find()
操作执行时间。 Also, see about server-side JavaScript execution: Running .js files via a mongo shell Instance on the Server 另外,请参阅服务器端JavaScript执行: 通过服务器上的mongo shell实例运行.js文件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.