Search code examples
mysqlmongodbjoinmongodb-querynosql-aggregation

Join two collectios and update in MongoDB


Is there any equivalent to below MYSQL query in MongoDB?

update table_name1 as a
join table_name2 as b
on a.uniqueid=b.uniqueid
set a.column1=b.column1,a.column2=b.column2 ;

lookup might be a possible solution but don't know how to use it for updating.


Solution

  • You can do something like this,

    db.table1.find({}).forEach(function (t1) { // foreach on table one
        var t2 = db.table2.findOne({ uniqueid: t1.uniqueid}, 
                 { column1: 1,column2:1 }); // finding unique id of table1 with table2
        if (t2 != null) { // checking if not null
            t1.column1 = t2.column1; // assigning tabl2's value to table1
            db.table1.save(t1); // save it
        }
    });
    

    Please remove my comments