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
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With