Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update a collection based on another collection in MongoDB?

Tags:

Now I get two collections: coll01 and coll02.

And the structure of coll01 is like this:

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

and the structure of coll02 is like:

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

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

And what I want to do in traditional SQL is :

update coll01, coll02 set coll01.name = coll02.name where coll01.id = coll02.id 
like image 863
Jane Avatar asked Nov 06 '13 21:11

Jane


People also ask

How do I link two collections in MongoDB?

We can join documents on collections in MongoDB by using the $lookup (Aggregation) function. $lookup(Aggregation) creates an outer left join with another collection and helps to filter data from merged data.

Can you link collections in MongoDB?

Join Collections MongoDB is not a relational database, but you can perform a left outer join by using the $lookup stage. The $lookup stage lets you specify which collection you want to join with the current collection, and which fields that should match.


1 Answers

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?

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

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

like image 83
Shad Avatar answered Oct 15 '22 06:10

Shad