A simple mongoDB trick to save your time

Update all documents with just 2 line of code

Sometimes, we need to add a single field to all the documents in the database of a collection. Adding this field one by one can be time-consuming, especially with large documents. Developer often find themselves daunted by this task. But fear not! you can now accomplish this with just two lines of code.

here’s an example –
before integrating this code, consider a single object –
{
"_id": "6565c912dc088bc26ee365d0",
"title": "Grilled Chicken Salad",
"image": "https://i.ibb.co/YbPcf1k/khloe-arledge-V7hibs9xhe4-unsplash.jpg",
"category": "lunch",
"price": 10.99,
"likes": 2,
"reviews": 0,
"name": "Jahid",
"email": "[email protected]"
}

Now, add thse following code to the server side –

// Accessing the collection
const reqMealCollection = client.db(“hosteldb”).collection(“requestedMeals”);

// Update all documents by adding the ‘status’ field if it doesn’t exist,
// assigning the value “pending” to each new document.
reqMealCollection.updateMany(
{ status: { $exists: false } },
{ $set: { status: “pending”} }
);

now close the server and start it again. here is the result after implementing this code –

{
"_id": "6565c912dc088bc26ee365d0",
"title": "Grilled Chicken Salad",
"image": "https://i.ibb.co/YbPcf1k/khloe-arledge-V7hibs9xhe4-unsplash.jpg",
"category": "lunch",
"price": 10.99,
"likes": 2,
"reviews": 0,
"name": "Jahid",
"email": "[email protected]",
"status": "pending" // newly added field
}

And if you want to remove any field, simply use this code:

// removing status field
{ status: "pending"},
{ $unset: { status: ""} }

result –
{
"_id": "6565c912dc088bc26ee365d0",
"title": "Grilled Chicken Salad",
"image": "https://i.ibb.co/YbPcf1k/khloe-arledge-V7hibs9xhe4-unsplash.jpg",
"category": "lunch",
"price": 10.99,
"likes": 2,
"reviews": 0,
"name": "Jahid",
"email": "[email protected]",
// "status" field has been removed
}

feel free to adapt and integrate this approach into your workflow for efficient document management. Thanks me later !


Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top
Martins ad network.