DEV Community

Jahid2121
Jahid2121

Posted on

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": "jahidhasan20u@gmail.com"
}

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": "jahidhasan20u@gmail.com",
"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": "jahidhasan20u@gmail.com",
// "status" field has been removed
}

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

Top comments (0)