Mongo updates one table based on data from another table
In business scenarios, there is often a requirement to update a field of table B according to the information in table A. In a relational database, this requirement is very simple, and a SQL is done:
Update B set B.f1=A.a1 where xxxx
But in the mongo database, a SQL cannot be solved. Fortunately, mongo supports js scripts, which can be implemented through js writing similar to stored procedures. For example, in a business scenario, there is a user table, a vehicle table, and the status of the vehicle table is summarized into the user table.
Var cursor = db.getCollection ('vehicle') .aggregate ([{$match: {' checkStatus':2}}, {$group: {_ id: "$userId", vehicleNum: {$sum:1}]) while (cursor.hasNext ()) {r = cursor.next (); print (r ["_ id"] + "\ t" + r ["vehicleNum"]) Db.getCollection ("user") .update ({_ id: r ["_ id"]}, {$set: {vehicleNum: r ["vehicleNum"], updateDatetime: ISODate ("2019-05-23T09:07:56.566+08:00")}})}
This principle is very simple, that is, according to mongo return cursor traversal, as long as you know how to access the cursor node can be easily written out.