Update data across multiple collections within the same database

I’m new to MongoDB and trying to learning how to update data across multiple collections within the same database. I looked at transactions as per the blog below but the Airbnb example seems overly complicated.
https://www.mongodb.com/developer/quickstart/node-transactions/

I also came across this stackoverflow post where one could use Promise, Await/Sync or $lookup.
I do not know how to apply this in my use case and if there is an easier way

To keep it simple, I’m trying to update a field in two collections using a single query.

For Example: Lets take the sample_analytics database within MongoDB as shown below. We have an accounts collection and a customers collection.

Screen Shot 2021-08-11 at 1.09.38 pm

My query:

If I update an account number in the accounts array in the customer collection, how to update the same account number in the accounts collection. I was wondering if this is possible with a single update query.

Hello @Jagjit_Singh, here is the information you are looking for.

You can update a document in two collections. And the operation can be performed atomically using MongoDB Transaction. But, the update operation on each collection will be separate - it cannot be done as a “single query”.


You can do this with two separate update operations - one each on a collection. To make both the updates (together) atomic, use a transaction.

Here is a simple example with two insert operations on two collections, inserting a document in each one - within a transaction. This runs in mongosh.

1 Like

Thanks Prasad. I was able to update two collections using the script below but not sure if its the right approach, for example i wasn’t able to check if the user exists in the comments collections.

The script updates the email field value in the users and comments collection in the sample_mflix database in MongoDB.

How can we write the below using transactions? That will be great help.

const { MongoClient } = require('mongodb');

async function main() {
   
    const uri = "mongodb+srv:<username>:<password>@<your-cluster-url>/sample_mflix?retryWrites=true&w=majority";

  
    const client = new MongoClient(uri);

    const userName = "Ned Stark"
    const newEmail = "nedstark@gmail.com"

    try {
        // Connect to the MongoDB cluster
        await client.connect();

        //user and comments collection
        users = client.db("sample_mflix").collection("users")
        comments = client.db("sample_mflix").collection("comments")

        //check if the user to be updated exists
        const filteredName = await users.find({name:userName})
        if ((await filteredName.count()) === 0) {
            console.log("No user found!");
          }
        
        //update email in the users collection
        userUpdate = await users.updateOne(
            { name: `${userName}`},
            { $set: { email: newEmail } },
          );
        console.log(`Updated ${userUpdate.modifiedCount} documents in users collections`);
        
        //update email in the comments collection
        commentUpdate = await comments.updateMany(
            { name: `${userName}`},
            { $set: { email: newEmail } },
        );

        console.log(`Updated ${commentUpdate.modifiedCount} documents in comments collections`);


        } catch (err) {
          console.error(`Something went wrong: ${err}`);
        }
        finally {
        await client.close();
        }
    }

main().catch(console.error);

@Jagjit_Singh,

What are the results you are seeing when you run your above script?

Generally, when you update a document in a collection the data (i.e, the document) gets modified based upon the query filter and the update. So, please verify those and see what is happening with your code and the data.

For information about how to update documents and some examples, please study the documentation from the following two links. There is also a MongoDB University’s free video based online course to learn about programming using NodeJS Driver (see the third link below).

The script works and updates the documents in the two collections. I’m hoping to achieve the same using transactions which i’m finding difficult to apply. I have reviewed the documentation links but didnt help.

Even the above script I managed to get it working reading the documentation on mongodb but the transactions documentation does not have simple examples.

@Jagjit_Singh, this is a similar example (as I had linked earlier using mongosh) of using MongoDB transactions with NodeJS driver. This is as simple as it can get regarding transactions.

I don’t know your level of expertise regarding MongoDB or transactions or NodeJS. If you are finding it difficult with these issues in general together or individually - I suggest post individual and specific questions - one at a time.

I believe, I have already provided reasonable information for your question(s).