MongoDB CRUD Operations: Replace and Delete Documents

MongoDB CRUD Operations: Replace and Delete Documents

Lesson 1: Replacing a Document in MongoDB

  1. Lab: Replacing a Document in MongoDB
    To replace a document in MongoDB while retaining the original document's
    _idfield, follow these steps:

    1. Find the document with acommon_name of "Northern Cardinal" and take note of its _id field.

    2. Use the_id to create a query that will replace the "Northern Cardinal" document with the new document.

    3. 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.

  1. Quiz: Replacing a Document in MongoDB

    1. 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).

    2. 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" }


Lesson 2: Updating MongoDB Documents by Using updateOne()

  1. Lab: Updating MongoDB Documents by Using updateOne()
    To update a document by adding a new field in MongoDB, follow these steps:

    1. Find the document with acommon_name of "Canada Goose" and examine its contents.

    2. Update the document by adding a new field titledtags.

    3. 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");
  1. To add elements to an array field within a document in MongoDB without removing any existing values, you can use the $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:

  1. Write a query to update the document with the specified_id and add the new elements to the diet array.

  2. Verify that the update was successful and thediet array 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

  1. Write a query to find the document withcommon_name of "Robin Redbreast".

  2. Use the$inc operator to increment the sightings field by 1.

  3. Set a new fieldlast_updated to the current date and time using new Date().

  4. Add theupsert option 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 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.

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()

  1. You want to add an element to the 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

  1. 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