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

Now I get two collections: coll01 and coll02 .

And the structure of coll01 is as follows:

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

and the structure of coll02 is similar:

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

The two id fields in both collections are indexes. And the number of documents in these two collections is the same.

And what I want to do in traditional SQL:

 update coll01, coll02 set coll01.name = coll02.name where coll01.id = coll02.id 
+6
source share
1 answer

Mongodb is not a relational database and does not support federation. So you should think a bit, do you really need mongodb for your purposes?

Update solution: you can update each document with coll01 in a 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); } }); 

A pointer to the id field in the coll02 collection coll02 reduce the execution time of the find() operation inside the loop. Also, look at server-side JavaScript execution: Running .js files through the mongo shell Instance on the server

+12
source

Source: https://habr.com/ru/post/957542/


All Articles