# 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**`_id`**field, follow these steps:**
    
    1. **Find the document with a**`common_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`.
    
    ```javascript
    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`.
    
    ```javascript
    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.
    
    ```javascript
    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:
    
    ```javascript
    {
       "acknowledged": true,
       "insertedId": null,
       "matchedCount": 1,
       "modifiedCount": 1,
       "upsertedCount": 0
    }
    ```
    
    This confirms that the document was successfully replaced while retaining the original `_id`.
    
2. **Quiz: Replacing a Document in MongoDB**
    
    1. **Which of the following statements regarding the**`replaceOne()`**method for the MongoDB Shell (**`mongosh`**) are true? (Select all that apply.)**  
        <mark>A. This method is used to replace a single document that matches the filter document.</mark>  
        <mark>B. This method accepts a filter document, a replacement document, and an optional options document.</mark>  
        C. This method can replace multiple documents in a collection.  
        <mark>D. This method returns a document containing an acknowledgement of the operation, a matched count, modified count, and an upserted ID (if applicable).</mark>
        
    2. **You want to replace the following document from the**`birds`**collection 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.)**
        
    
    ```php
    { _id: ObjectId("6286809e2f3fa87b7d86dccd") },
      {
        common_name: "Morning Dove",
        habitat: ["urban areas", "farms", "grassland"],
        diet: ["seeds"]
      }
    ```
    
    * **<mark>A.</mark>** <mark> { _id: ObjectId("6286809e2f3fa87b7d86dccd") }</mark>
        
    * **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 a**`common_name` of "Canada Goose" and examine its contents.
        
    2. **Update the document by adding a new field titled**`tags`.
        
    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.
    
    ```javascript
    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.
    
    ```javascript
    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.
    
    ```javascript
    printjson(updateResult);
    ```
    
    The expected output should be:
    
    ```javascript
    {
      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.
    
    ```javascript
    const updatedCanadaGoose = db.birds.findOne({ common_name: "Canada Goose" });
    printjson(updatedCanadaGoose);
    ```
    
    The expected output should include the new `tags` field:
    
    ```javascript
    {
      _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:
    
    ```javascript
    load("/app/restoreData.js");
    ```
    
    2. 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 the**`diet` array has been updated.
        
    
    ### Step 1: Update the Document
    
    Use the `$addToSet` update operator to add the elements to the `diet` array.
    
    ```javascript
    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:
    
    ```javascript
    {
      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.
    
    ```javascript
    const updatedDocument = db.birds.findOne({ _id: ObjectId("6268471e613e55b82d7065d7") });
    printjson(updatedDocument);
    ```
    
    The `diet` array in the output should now include the new elements:
    
    ```javascript
    {
      _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 with**`common_name` of "Robin Redbreast".
        
    2. **Use the**`$inc` operator to increment the `sightings` field by 1.
        
    3. **Set a new field**`last_updated` to the current date and time using `new Date()`.
        
    4. **Add the**`upsert` option to create a new document if no documents match the query.
        
    
    ### Example Query
    
    ```javascript
    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:
    
    ```javascript
    {
      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:
    
    ```javascript
    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.
    
    ```javascript
     { $set: { items:[{ “name”: "tablet", “price”: 200}] } }
    ```
    
    B.
    
    ```javascript
     { $update: { items:[{ “name”: "tablet", “price”: 200}] } }
    ```
    
    C.
    
    ```javascript
     { $push: { items:[{ “name”: "tablet", “price”: 200}] } }
    ```
    
    D.
    
    ```javascript
     { $upsert: { items:[{ “name”: "tablet", “price”: 200}] } }
    ```
    
    * **A.** Option A
        
    * **B.** Option B
        
    * **<mark>C.</mark>** <mark> Option C</mark>
        
    * **D.** Option D
        
2. **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.)**
    
    ```javascript
    {
      _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.
    
    ```javascript
     { $set: {result: ‘Pass’} }
    ```
    
    B.
    
    ```javascript
     { $upsert: {result: ‘Pass’} }
    ```
    
    C.
    
    ```javascript
     { $insert: {result: ‘Pass’} }
    ```
    
    D.
    
    ```javascript
     { $push: {result: ‘Pass’} }
    ```
    
    * **<mark>A.</mark>** <mark> Option A</mark>
        
    * **B.** Option B
        
    * **C.** Option C
        
    * **D.** Option D
