Table of Contents
Lesson 1: Replacing a Document in MongoDB
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 a
common_nameof "Northern Cardinal" and take note of its_idfield.Use the
_idto 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:
Step 1: Find the Document and Note the _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);
Step 2: Replace the Document
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"]
}
);
Step 3: Verify the Operation
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 the
replaceOne()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 the
birdscollection 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" }
Lesson 2: Updating MongoDB Documents by Using updateOne()
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 a
common_nameof "Canada Goose" and examine its contents.Update the document by adding a new field titled
tags.Verify the operation was successful and check if the new field was added.
Step 1: Find the Document
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);
Step 2: Update the Document
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);
Step 3: Verify the Operation
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
}
Step 4: Verify the New Field
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");
- To add elements to an array field within a document in MongoDB without removing any existing values, you can use the
$addToSetupdate 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$pushoperator with the$eachmodifier.
Here’s how you can achieve this:
Write a query to update the document with the specified
_idand add the new elements to thedietarray.Verify that the update was successful and the
dietarray has been updated.
Step 1: Update the Document
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
}
Step 2: Verify the Updated Document
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.
Step-by-Step Instructions
Write a query to find the document with
common_nameof "Robin Redbreast".Use the
$incoperator to increment thesightingsfield by 1.Set a new field
last_updatedto the current date and time usingnew Date().Add the
upsertoption to create a new document if no documents match the query.
Example 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);
Explanation
Filter Document:
{ common_name: "Robin Redbreast" }- This filter searches for the document with the specified common name.Update Document:
{ $inc: { sightings: 1 } }- This increments thesightingsfield by 1.{ $set: { last_updated: new Date() } }- This sets thelast_updatedfield to the current date and time.
Options:
{ upsert: true }- This ensures that if no matching document is found, a new document is created.
Expected Output
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
}
Verify the Operation
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.
Quiz: Updating MongoDB Documents by Using updateOne()
- You want to add an element to the
itemsarray 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
resultsfield 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
