简体   繁体   English

如何根据MongoDB中的另一个集合更新集合?

[英]How to update a collection based on another collection in MongoDB?

Now I get two collections: coll01 and coll02 . 现在我得到两个集合: coll01coll02

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.

相关问题 MongoDB:根据另一个集合更新一个集合 - MongoDB: update a collection based on another collection 基于MongoDB中另一个集合中的数据更新集合 - Update collection based on data in another collection in MongoDB 基于另一个集合更新集合的字段 - MongoDB - Update field of a collection based on another collection - MongoDB 如何基于MongoDB中的另一个集合嵌入字段值更新嵌入集合字段的数组? - How to update array of embedded collection field based on another collection embedded field value in MongoDB? 如何在mongodb集合中创建文档并同时更新另一个集合 - how to create a document in a mongodb collection and update another collection in the same time 如何使用另一个集合中的值更新 MongoDB 集合? - How do I update a MongoDB collection with values from another collection? 如何使用对另一个集合的聚合查询结果更新/插入 mongodb 集合 - How to update/insert into a mongodb collection with the result of aggregate query on the another collection 如何使用另一个集合中的字段值更新Mongodb集合中的文档 - How to update document in Mongodb collection with a field value from another collection 如何根据存储在另一个集合中的数据在 MongoDB 集合中搜索文本? - How to search for text in a MongoDB collection based on data stored in another collection? 如何更新mongodb中的集合 - how to update a collection in mongodb
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM