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.
New & Unread Topics
Topic | Replies | Views | Activity |
---|---|---|---|
Moving data around in an aggregation stage | 5 | 341 | Jun 2024 |
How to find and fix documents with duplicate keys? | 0 | 387 | Jun 2024 |
Does MongoDB use any data structures other than B-trees for its indexes? | 0 | 35 | Sep 2024 |
Is it possible to restrict the impact of a single user can have in a database | 0 | 32 | Dec 2024 |
“$ne: null not working as expected to filter document field inside of array | 0 | 48 | Jan 10 |