2 / 3
Apr 9

Having same key value in multiple collection. For eg. productName; “Test”. From master screen if I update it, it should get updated in all collection where we have productName key and value Test. If we are using mongodb to avoid relational data and store data in format of json, then how we can handle this above situation. Is their any feature, function mongo provided to use or we need to keep track of collection where we have productName Test

MongoDB doesn’t have an API/command to update multiple collections at the same time. But you could have a list of collection names and call the update command on each:

const collectionNames = ['users', 'products', 'orders']; // or const collectionNames = db.getCollectionNames(); for (const collectionName of collectionNames) { updateResult = await db.getCollection(collectionName).updateOne( { productName: 'Test' }, // filterCriteria { $set: { productName: 'Final' } } // updateOperation ); }

If you have this scnario happening frequently for different fields, put that into a function which accepts a filter and update operation and does the collection loop:

async function updateAllCollections(filterCriteria, updateOperation) { // put that loop here } await updateAllCollections({ productName: 'Test' }, { $set: { productName: 'Final' } }); await updateAllCollections({ _id: 123 }, { $set: { status: 'Ready' } });

May I have suggestion on this solution. Suppose I have clientMaster, clientBranchMaster, clientProductMaster, clientCaseStatusMaster, clientContractMaster. Each collection have clientId, clientName and their respective details, some details have array of obj. So to update clientName in each collection, can I do only one document in master collection having array of object of each collection which id depend on clientId like mentioned above collection. If we keep this nested json structure, will indexing work fast while updating or inserting document. I want suggestion for this approach.