# MongoDB CRUD Operations in Python

## **Overview**

In this unit, you'll learn how to perform CRUD operations by using Python. First, you'll learn how BSON documents are represented in Python. Next, you'll learn how to insert, query and retrieve, update, and delete documents in a Python application. Finally, you'll learn how to create a multi-document transaction.

### LESSON 1: WORKING WITH MONGODB DOCUMENTS IN PYTHON

1. **What Python data type is used to represent MongoDB documents? (Select one.)**
    
    **A.** Document
    
    **<mark>B.</mark>** <mark> Dictionary</mark>
    
    **C.** List
    
2. **You want to insert data stored in a Python dictionary to a new document in your MongoDB collection using the PyMongo driver. What do you need to do to convert a Python dictionary to BSON? (Select one.)**
    
    **<mark>A.</mark>** <mark> Nothing, the dictionary will be automatically converted by the driver to a MongoDB BSON document.</mark>
    
    **B.** Reference an independent library that will help you convert the data from a dictionary to BSON.
    
    **C.** Add an \_id field with an ObjectID value to the dictionary so it can be automatically converted to a MongoDB BSON document by the driver.
    

### LESSON 2: INSERTING A DOCUMENT IN PYTHON APPLICATIONS

1. **You need to insert a new restaurant into the**`restaurants`**collection. The new restaurant’s data is stored in a Python dictionary, stored in the variable name**`hyderabadi_biryani`**. Which of the following expressions will insert the new document into the**`restaurants`**collection? (Select one.)**
    
    **A.**
    
    ```javascript
    result = restaurants.insert_one(hyderabadi_biryani)
    ```
    
    **B.**
    
    ```javascript
    result = restaurants.insert(hyderabadi_biryani)
    ```
    
    **C.**
    
    ```javascript
    result = restaurants.insert_many(hyderabadi_biryani)
    ```
    
    **D.**
    
    ```javascript
    result = restaurants.insert.hyderabadi_biryani
    ```
    
    **<mark>A.</mark>** <mark> Option A</mark>
    
    **B.** Option B
    
    **C.** Option C
    
    **D.** Option D
    
2. **The**`sample_restaurants`**database is expanding to include restaurants in 5 new neighborhoods. You need to add documents for the 5 new neighborhoods in the neighborhoods collection. Documents for each new neighborhood are stored in the**`neighborhood_update`**variable. Which expression should you use to insert these documents into the collection? (Select one.)**
    
    **A.**
    
    ```javascript
    result = neighborhoods_collection.insert_one(neighborhood_update)
    ```
    
    **B.**
    
    ```javascript
    result = neighborhoods_collection.insert_many(neighborhood_update)
    ```
    
    **C.**
    
    ```javascript
    result = neighborhoods_collection.insert(neighborhood_update)
    ```
    
    **D.**
    
    ```javascript
    result = neighborhoods_collection.insert_one([neighborhood_one,neighborhood_two, neighborhood_three, neighborhood_four, neighborhood_5])
    ```
    
    **A.** Option A
    
    **<mark>B.</mark>** <mark> Option B</mark>
    
    **C.** Option C
    
    **D.** Option D
    

### LESSON 3: QUERYING A MONGODB COLLECTION IN PYTHON APPLICATIONS

1. **You need to find the population for the 85281 zip code in Tempe, Arizona. You want the results of the specific document returned to you directly within the terminal. Which query should you use to assign the result to the**`result`**variable, given the following? (Select one.)**
    
    ```powershell
    #Get reference to the sample_training database
    db = client.sample_training
    
    #Get reference to zips collection
    zips_collection = db.zips
    
    #Filter document for Tempe zip code
    tempe_zip = {"zip": "85281"}
    ```
    
    **A.**
    
    ```javascript
    result = sample_training.zips.find({“zip”: “85281”})
    ```
    
    **B.**
    
    ```javascript
    result = zips_collection.find(tempe_zip)
    ```
    
    **C.**
    
    ```javascript
    result = zips_collection.find_one(tempe_zip)
    ```
    
    **D.**
    
    ```javascript
    result = zips.find_one(“zip”: “85281”)
    ```
    
    **A.** Option A
    
    **B.** Option B
    
    **<mark>C.</mark>** <mark> Option C</mark>
    
    **D.** Option D
    
2. **You need to find all zip codes for the city of Tulsa, Oklahoma. Which query should you use, given the following? (Select one.)**
    
    ```apache
    # Get reference to 'sample_training' database
    db = client.sample_training
    
    # Get a reference to the 'zips' collection
    zips_collection = db.zips
    
    # Query
    tulsa_documents = {"city": "TULSA"}
    
    # Select an expression that selects the documents matching the query constraint in the 'zips' collection.
    cursor =
    ```
    
    **A.**
    
    ```javascript
    cursor = zips_collection.find(tulsa_documents)
    ```
    
    **B.**
    
    ```javascript
    cursor = zips_collection.find_one(tulsa_documents)
    ```
    
    **C.**
    
    ```javascript
    cursor = zips_collection.find_one("city": "TULSA")
    ```
    
    **D.**
    
    ```javascript
    cursor = zips_collection.find("city": "TULSA")
    ```
    
    **<mark>A.</mark>** <mark> Option A</mark>
    
    **B.** Option B
    
    **C.** Option C
    
    **D.** Option D
    

### LESSON 4: UPDATING DOCUMENTS IN PYTHON APPLICATIONS

1. **Zvents recently hired 15 new employees, bringing the total number of employees to 70. You need to update the**`companies`**collection within the**`sample_training`**database, so the**`number_of_employees`**field is set to 70. Which query should you use, given the following? (Select one.)**
    
    ```apache
    # Get reference to 'sample_training' database
    db = client.sample_training
    
    # Get reference to 'companies' collection
    companies_collection = db.companies
    
    # Filter
    document_to_update = {"name": "Zvents"}
    
    # Update
    update_employees = {"$set": {"number_of_employees": 70 }}
    
    # Select an expression that updates the number of employees.
    ```
    
    **A.**
    
    ```javascript
     result = db.companies.update_one({document_to_update, update_employees})
    ```
    
    **B.**
    
    ```javascript
     result = companies_collection.update_one({ document_to_update}, { update_employees})
    ```
    
    **C.**
    
    ```javascript
    result = companies_collection.update( document_to_update,  update_employees)
    ```
    
    **D.**
    
    ```javascript
    result = companies_collection.update_one(document_to_update, update_employees)
    ```
    
    **A.** Option A
    
    **B.** Option B
    
    **C.** Option C
    
    **<mark>D.</mark>** <mark> Option D</mark>
    
2. **The**`companies`**collection is missing data on the initial public offerings (IPO) for Linkedin and Facebook. Given the python file below, select the expression that sets the**`ipo`**field to**`True`**for the two companies. (Select one).**
    
    ```powershell
    # Get reference to 'sample_training' database
    db = client.sample_training
    
    # Get reference to 'accounts' collection
    companies_collection = db.companies
    
    # Filter
    select_companies = {"name": { "$in" : ["Facebook", "LinkedIn"]}}
    
    # Update
    set_ipo = {"$set": {"ipo": True}}
    
    # Select an expression that sets the value of "ipo" to True for Facebook and Linkedin
    ```
    
    **A.**
    
    ```javascript
     result = sample_training.update_many(select_companies, set_ipo)
    ```
    
    **B.**
    
    ```javascript
     result = companies_collection.update_many(select_companies, set_ipo)
    ```
    
    **C.**
    
    ```javascript
    result = companies.update(select_companies, set_ipo)
    ```
    
    **D.**
    
    ```javascript
     result = companies_collection.update_many[select_companies, set_ipo]
    ```
    
    **A.** Option A
    
    **<mark>B.</mark>** <mark> Option B</mark>
    
    **C.** Option C
    
    **D.** Option D
    

### LESSON 5: DELETING DOCUMENTS IN PYTHON APPLICATIONS

1. **Use this dataset to answer the question that follows:**
    
    ```javascript
      {
        "account_id": "MDB156014571",
        "account_holder": "Adelen Værnes",
        "account_type": "savings",
        "balance": 1519.62,
        "transfers_complete": [
          "TR670287839",
          "TR679752211",
          "TR854525844",
          "TR762109284"
        ]
      },
      {
        "account_id": "MDB190468049",
        "account_holder": "Louis Lewis",
        "account_type": "savings",
        "balance": 4155.67,
        "transfers_complete": [
          "TR859060098",
          "TR729044189",
          "TR126484922",
          "TR617907396",
          "TR598541455"
        ]
      },
      {
        "account_id": "MDB870205338",
        "account_holder": "Juan Perez",
        "account_type": "checking",
        "balance": 1907.8,
        "transfers_complete": [
          "TR432759196",
          "TR797654953",
          "TR391563093",
          "TR464853424",
          "TR922604241"
        ]
      },
    ```
    
    **When you run the following command, what is the result? (Select one.)**
    
    ```javascript
    filter = { account_type: "checking" }
    result = db.accounts.delete_many(filter)
    ```
    
    **<mark>A.</mark>** <mark> Louis Lewis and Adelen Værnes are the only two documents left in the collection.</mark>
    
    **B.** Juan Perez is the only document left in the collection.
    
    **C.** No changes happen to the collection.
    
    **D.** The account\_type checking field is deleted from every document in the collection.
    
2. **A bank has identified a fraudulent account with the**`account_id`**of**`MDB905411541`**. Given the python file below, which expression should you use to remove this account? (Select one.)**
    
    ```powershell
    
    # Get reference to 'bank' database
    db = client.bank
    
    # Get a reference to the 'accounts' collection
    accounts_collection = db.accounts
    
    # Filter by ObjectId
    fraud_account = {"account_id":"MDB905411541"}
    
    # Select an expression that deletes the target account.
    ```
    
    **A.**
    
    ```javascript
     result = accounts_collection.delete(fraud_account)
    ```
    
    **B.**
    
    ```javascript
    result = accounts_collection.hide(fraud_account)
    ```
    
    **C.**
    
    ```javascript
    result = accounts_collection.delete(account)
    ```
    
    **D.**
    
    ```javascript
     result = accounts_collection.delete_one(fraud_account)
    ```
    
    **A.** Option A
    
    **B.** Option B
    
    **C.** Option C
    
    **<mark>D.</mark>** <mark> Option D</mark>
    

### LESSON 6: CREATING MONGODB TRANSACTIONS IN PYTHON APPLICATIONS

1. **Use this code to answer the question that follows:**
    
    ```javascript
    def callback(
        session,
        transfer_id=None,
        account_id_receiver=None,
        account_id_sender=None,
        transfer_amount=None,
    ):
    
    accounts_collection = session.client.bank.accounts
    
    transfers_collection = session.client.bank.transfers
    
    transfer = {
        "transfer_id": transfer_id,
        "to_account": account_id_receiver,
        "from_account": account_id_sender,
        "amount": {"$numberDecimal": transfer_amount},
    }
    
    accounts_collection.update_one(
        {"account_id": account_id_sender},
        {
            "$inc": {"balance": -transfer_amount},
            $push": {"transfers_complete": transfer_id},
        },
        session=session,
    )
    
    accounts_collection.update_one(
        {"account_id": account_id_receiver},
        {
            "$inc": {"balance": transfer_amount},
            "$push": {"transfers_complete": transfer_id},
        },
        session=session,
    )
    
    transfers_collection.insert_one(transfer, session=session)
    
    print(“Transaction successful”) 
    
    return
    
    def callback_wrapper(s):
    callback(
        s,
        transfer_id="TR218721873",
        account_id_receiver="MDB343652528",
        account_id_sender="MDB574189300",
        transfer_amount=100,
    )
    ```
    
    **If one of the operations fails, what will happen to the other operations in the transaction? (Select all that apply.)**
    
    **A.** The operations that did not fail will be reversed.
    
    **<mark>B.</mark>** <mark> The entire transaction will be canceled, and no operations will be committed.</mark>
    
    **C.** The entire transaction will complete, but only the operations that did not fail will be committed.
