Get the App
SLTechnology News&Howtos  ›  Database  › 

Mongo updates one table based on data from another table

Shulou Source: shulou.com Published: 2022-06-01 21:56:15 09月28日 Update

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.

Tags: Data business scenarios that is databases methods cursors users vehicles requirements user tables updates information principles can be passed through fields status scripts nodes processes Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia vpn Huawei macOS Shulou Tech Info