MongoDB CRUD Operations in Python

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

    B. Dictionary

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

    A. Nothing, the dictionary will be automatically converted by the driver to a MongoDB BSON document.

    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 therestaurantscollection. The new restaurant’s data is stored in a Python dictionary, stored in the variable namehyderabadi_biryani. Which of the following expressions will insert the new document into therestaurantscollection? (Select one.)

    A.

     result = restaurants.insert_one(hyderabadi_biryani)
    

    B.

     result = restaurants.insert(hyderabadi_biryani)
    

    C.

     result = restaurants.insert_many(hyderabadi_biryani)
    

    D.

     result = restaurants.insert.hyderabadi_biryani
    

    A. Option A

    B. Option B

    C. Option C

    D. Option D

  2. Thesample_restaurantsdatabase 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 theneighborhood_updatevariable. Which expression should you use to insert these documents into the collection? (Select one.)

    A.

     result = neighborhoods_collection.insert_one(neighborhood_update)
    

    B.

     result = neighborhoods_collection.insert_many(neighborhood_update)
    

    C.

     result = neighborhoods_collection.insert(neighborhood_update)
    

    D.

     result = neighborhoods_collection.insert_one([neighborhood_one,neighborhood_two, neighborhood_three, neighborhood_four, neighborhood_5])
    

    A. Option A

    B. Option B

    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 theresultvariable, given the following? (Select one.)

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

     result = sample_training.zips.find({“zip”: “85281”})
    

    B.

     result = zips_collection.find(tempe_zip)
    

    C.

     result = zips_collection.find_one(tempe_zip)
    

    D.

     result = zips.find_one(“zip”: “85281”)
    

    A. Option A

    B. Option B

    C. Option C

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

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

     cursor = zips_collection.find(tulsa_documents)
    

    B.

     cursor = zips_collection.find_one(tulsa_documents)
    

    C.

     cursor = zips_collection.find_one("city": "TULSA")
    

    D.

     cursor = zips_collection.find("city": "TULSA")
    

    A. Option A

    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 thecompaniescollection within thesample_trainingdatabase, so thenumber_of_employeesfield is set to 70. Which query should you use, given the following? (Select one.)

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

      result = db.companies.update_one({document_to_update, update_employees})
    

    B.

      result = companies_collection.update_one({ document_to_update}, { update_employees})
    

    C.

     result = companies_collection.update( document_to_update,  update_employees)
    

    D.

     result = companies_collection.update_one(document_to_update, update_employees)
    

    A. Option A

    B. Option B

    C. Option C

    D. Option D

  2. Thecompaniescollection is missing data on the initial public offerings (IPO) for Linkedin and Facebook. Given the python file below, select the expression that sets theipofield toTruefor the two companies. (Select one).

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

      result = sample_training.update_many(select_companies, set_ipo)
    

    B.

      result = companies_collection.update_many(select_companies, set_ipo)
    

    C.

     result = companies.update(select_companies, set_ipo)
    

    D.

      result = companies_collection.update_many[select_companies, set_ipo]
    

    A. Option A

    B. Option B

    C. Option C

    D. Option D

LESSON 5: DELETING DOCUMENTS IN PYTHON APPLICATIONS

  1. Use this dataset to answer the question that follows:

       {
         "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.)

     filter = { account_type: "checking" }
     result = db.accounts.delete_many(filter)
    

    A. Louis Lewis and Adelen Værnes are the only two documents left in the collection.

    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 theaccount_idofMDB905411541. Given the python file below, which expression should you use to remove this account? (Select one.)

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

      result = accounts_collection.delete(fraud_account)
    

    B.

     result = accounts_collection.hide(fraud_account)
    

    C.

     result = accounts_collection.delete(account)
    

    D.

      result = accounts_collection.delete_one(fraud_account)
    

    A. Option A

    B. Option B

    C. Option C

    D. Option D

LESSON 6: CREATING MONGODB TRANSACTIONS IN PYTHON APPLICATIONS

  1. Use this code to answer the question that follows:

     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.

    B. The entire transaction will be canceled, and no operations will be committed.

    C. The entire transaction will complete, but only the operations that did not fail will be committed.