MongoDB CRUD Operations: Replace and Delete Documents

A passionate full-stack developer from @ePlus.DEV
Search for a command to run...

A passionate full-stack developer from @ePlus.DEV
No comments yet. Be the first to comment.
MongoDB is a cross-platform document-oriented database program classified as a NoSQL database. MongoDB uses JSON-like documents with optional schemas. This makes it a flexible and powerful database
Overview In this unit, you will install a set of command-line tools on an Ubuntu Linux container that will help you with several tasks associated with administering and managing a MongoDB deployment. These common tasks for DBAs include: Backup and r...
Overview In a challenge lab you’re given a scenario and a set of tasks. Instead of following step-by-step instructions, you will use the skills learned from the labs in the course to figure out how to

🏕️ Arcade Base Camp August 2026 Welcome to Arcade Base Camp August 2026, where you’ll develop key Google Cloud skills and earn an exclusive credential that will open doors to the cloud for you. No pr

Một bản tin giúp Developer cập nhật nhanh AI, Cloud, Open Source và những công nghệ đáng chú ý trong ngày. 📌 Executive Summary Google Cloud giới thiệu hai Database Operations Agents hỗ trợ onboard

Một bản tin giúp Developer cập nhật nhanh AI, Cloud, Open Source và những công nghệ đáng chú ý trong ngày. 📌 Executive Summary SK hynix và Sandisk công bố đặc tả mở đầu tiên cho High Bandwidth Fla

Challenge overview In a challenge lab you’re given a scenario and a set of tasks. Instead of following step-by-step instructions, you will use the skills learned from the labs in the course to figure

Lab: Replacing a Document in MongoDB
To replace a document in MongoDB while retaining the original document's_idfield, follow these steps:
Find the document with acommon_name of "Northern Cardinal" and take note of its _id field.
Use the_id to create a query that will replace the "Northern Cardinal" document with the new document.
Verify the operation was successful.
Here's how you can perform these steps using the MongoDB shell:
_id First, find the document with the common_name of "Northern Cardinal" and take note of its _id.
use bird_data;
const northernCardinal = db.birds.findOne({ common_name: "Northern Cardinal" });
const cardinalId = northernCardinal._id;
printjson(northernCardinal);
Use the _id to replace the "Northern Cardinal" document with the new document. Make sure to keep the original _id.
db.birds.replaceOne(
{ _id: cardinalId },
{
_id: cardinalId, // Ensure the _id is retained
"common_name": "Morning Dove",
"scientific_name": "Zenaida macroura",
"wingspan_cm": 37.23,
"habitat": ["urban areas", "farms", "grassland"],
"diet": ["seeds"]
}
);
Verify that the operation was successful by checking the result of the replaceOne operation.
const result = db.birds.replaceOne(
{ _id: cardinalId },
{
_id: cardinalId, // Ensure the _id is retained
"common_name": "Morning Dove",
"scientific_name": "Zenaida macroura",
"wingspan_cm": 37.23,
"habitat": ["urban areas", "farms", "grassland"],
"diet": ["seeds"]
}
);
printjson(result);
The expected output should be:
{
"acknowledged": true,
"insertedId": null,
"matchedCount": 1,
"modifiedCount": 1,
"upsertedCount": 0
}
This confirms that the document was successfully replaced while retaining the original _id.
Quiz: Replacing a Document in MongoDB
Which of the following statements regarding thereplaceOne()method for the MongoDB Shell (mongosh) are true? (Select all that apply.)
A. This method is used to replace a single document that matches the filter document.
B. This method accepts a filter document, a replacement document, and an optional options document.
C. This method can replace multiple documents in a collection.
D. This method returns a document containing an acknowledgement of the operation, a matched count, modified count, and an upserted ID (if applicable).
You want to replace the following document from thebirdscollection with a new document that contains additional information on recent sightings, the scientific name of each species, and wingspan. What field should you use in the filter document to ensure that this specific document is replaced? (Select one.)
{ _id: ObjectId("6286809e2f3fa87b7d86dccd") },
{
common_name: "Morning Dove",
habitat: ["urban areas", "farms", "grassland"],
diet: ["seeds"]
}
A. { _id: ObjectId("6286809e2f3fa87b7d86dccd") }
B. { diet: ["seeds"] }
C. { habitat: ["urban areas"] }
D. { scientific_name: "Zenaida macroura" }
Lab: Updating MongoDB Documents by Using updateOne()
To update a document by adding a new field in MongoDB, follow these steps:
Find the document with acommon_name of "Canada Goose" and examine its contents.
Update the document by adding a new field titledtags.
Verify the operation was successful and check if the new field was added.
Run a findOne query for the document with a common_name of "Canada Goose" to examine its contents.
use bird_data;
const canadaGoose = db.birds.findOne({ common_name: "Canada Goose" });
printjson(canadaGoose);
Use the $set update operator to add a new field titled tags with the specified array of strings.
const updateResult = db.birds.updateOne(
{ common_name: "Canada Goose" },
{ $set: { tags: ["geese", "herbivore", "migration"] } }
);
printjson(updateResult);
Verify that the operation was successful by checking the result of the updateOne operation.
printjson(updateResult);
The expected output should be:
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
Run a findOne query again to ensure the new field tags was added to the document.
const updatedCanadaGoose = db.birds.findOne({ common_name: "Canada Goose" });
printjson(updatedCanadaGoose);
The expected output should include the new tags field:
{
_id: ObjectId("6268413c613e55b82d7065d2"),
common_name: 'Canada Goose',
scientific_name: 'Branta canadensis',
wingspan_cm: 152.4,
habitat: 'wetlands',
diet: [ 'grass', 'algae' ],
tags: [ 'geese', 'herbivore', 'migration' ]
}
If you encounter an issue where modifiedCount is 0, you may need to reload the data and attempt the lab again:
load("/app/restoreData.js");
$addToSet update operator. This operator ensures that the new elements are added to the array only if they do not already exist in it. If you want to ensure all elements are added regardless, use the $push operator with the $each modifier.Here’s how you can achieve this:
Write a query to update the document with the specified_id and add the new elements to the diet array.
Verify that the update was successful and thediet array has been updated.
Use the $addToSet update operator to add the elements to the diet array.
use bird_data;
const updateResult = db.birds.updateOne(
{ _id: ObjectId("6268471e613e55b82d7065d7") },
{ $addToSet: { diet: { $each: ["newts", "opossum", "skunks", "squirrels"] } } }
);
printjson(updateResult);
The expected output should be:
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
Run a findOne query to verify that the diet array has been updated.
const updatedDocument = db.birds.findOne({ _id: ObjectId("6268471e613e55b82d7065d7") });
printjson(updatedDocument);
The diet array in the output should now include the new elements:
{
_id: ObjectId("6268471e613e55b82d7065d7"),
common_name: "Some Bird Name",
scientific_name: "Some Scientific Name",
wingspan_cm: SomeNumber,
habitat: "Some Habitat",
diet: [ 'existingItem1', 'existingItem2', ..., 'newts', 'opossum', 'skunks', 'squirrels' ],
// other fields...
}
Make sure to replace "Some Bird Name", "Some Scientific Name", SomeNumber, and "Some Habitat" with the actual values from your document.
3. To update a document in the MongoDB birds collection using the common_name field, increment the sightings field, and set a new field last_updated to the current date and time, while also ensuring a new document is created if no documents match the query, you can use the updateOne method with the upsert option.
Write a query to find the document withcommon_name of "Robin Redbreast".
Use the$inc operator to increment the sightings field by 1.
Set a new fieldlast_updated to the current date and time using new Date().
Add theupsert option to create a new document if no documents match the query.
use bird_data;
const updateResult = db.birds.updateOne(
{ common_name: "Robin Redbreast" }, // Filter
{
$inc: { sightings: 1 }, // Increment sightings by 1
$set: { last_updated: new Date() } // Set last_updated to current date and time
},
{ upsert: true } // Create a new document if no match is found
);
printjson(updateResult);
Filter Document:{ common_name: "Robin Redbreast" } - This filter searches for the document with the specified common name.
Update Document:
{ $inc: { sightings: 1 } } - This increments the sightings field by 1.
{ $set: { last_updated: new Date() } } - This sets the last_updated field to the current date and time.
Options:
{ upsert: true } - This ensures that if no matching document is found, a new document is created.The expected output should indicate that the document was either updated or a new document was created:
{
acknowledged: true,
insertedId: ObjectId("..."), // This field will be null if the document was updated instead of inserted
matchedCount: 1, // This should be 1 if a document was found and updated
modifiedCount: 1, // This should be 1 if a document was found and updated
upsertedCount: 0 // This should be 0 if the document was updated, or 1 if a new document was created
}
To verify that the document was correctly updated or created, run a findOne query to check the contents of the updated or newly created document:
const robinRedbreast = db.birds.findOne({ common_name: "Robin Redbreast" });
printjson(robinRedbreast);
The output should show the sightings field incremented by 1 and the last_updated field set to the current date and time.
items array field in the sales collection. To do this, what should you include in the update document? (Select one.)A.
{ $set: { items:[{ “name”: "tablet", “price”: 200}] } }
B.
{ $update: { items:[{ “name”: "tablet", “price”: 200}] } }
C.
{ $push: { items:[{ “name”: "tablet", “price”: 200}] } }
D.
{ $upsert: { items:[{ “name”: "tablet", “price”: 200}] } }
A. Option A
B. Option B
C. Option C
D. Option D
Air France has recently passed inspection. In the following document, you need to update the results field from Fail to Pass. To do this, what should you include in your update document? (Select one.)
{
_id: ObjectId("56d61033a378eccde8a837f9"),
id: '31041-2015-ENFO',
certificate_number: 3045325,
business_name: 'AIR FRANCE',
date: 'Jun 9 2015',
result: 'Fail',
sector: 'Travel Agency - 440',
address: {
city: 'JAMAICA',
zip: 11430,
street: 'JFK INTL AIRPORT BLVD',
number: 1
}
}
A.
{ $set: {result: ‘Pass’} }
B.
{ $upsert: {result: ‘Pass’} }
C.
{ $insert: {result: ‘Pass’} }
D.
{ $push: {result: ‘Pass’} }
A. Option A
B. Option B
C. Option C
D. Option D