如何基于MongoDB中的另一个集合更新集合? [英] How to update a collection based on another collection in MongoDB?

查看:200
本文介绍了如何基于MongoDB中的另一个集合更新集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我得到两个集合:coll01coll02.

Now I get two collections: coll01 and coll02.

coll01的结构如下:

And the structure of coll01 is like this:

{
  id: 01,
  name: "xxx",
  age: 30
}

而coll02的结构如下:

and the structure of coll02 is like:

{
  id: 01,
  name: "XYZ"
  gender: "male"
}

两个集合中的两个id字段均为索引.并且这两个集合中的文档数是相同的.

The two id fields in the both collection are indices. And the numbers of documents in these two collections are same.

我想在传统SQL中做的是:

And what I want to do in traditional SQL is :

update coll01, coll02
set coll01.name = coll02.name
where coll01.id = coll02.id

推荐答案

Mongodb不是关系数据库,不支持连接数据库.因此,您应该考虑一下,您是否真的需要mongodb来实现您的目的?

Mongodb is not relational database and doesn't support join's. So, you should think a little, do you really need mongodb for your purposes?

更新解决方案:您可以循环地从coll01更新每个文档:

Solution for update: you can update each document from coll01 in loop:

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);
    }
});

集合中id字段的

索引将减少循环内的find()操作执行时间.另请参阅有关服务器端JavaScript执行的信息:通过服务器上的mongo shell实例运行.js文件

Index for id field in coll02 collection will decrease find() operation execution time inside the loop. Also, see about server-side JavaScript execution: Running .js files via a mongo shell Instance on the Server

这篇关于如何基于MongoDB中的另一个集合更新集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆