Inserting a single record using PyMongo

In order to produce actionable insights from your business intelligence system, you will more than likely need to combine data sources. Let us say that you have

Getting ready

In order to insert a record, we first create the record and then insert it. The new record needs to be in the JSON format.

How to do it…

from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.pythonbicookbook
customers = db.customers
import datetime
new_customer = {"first_name": "Bob",
                "last_name": "Smith",
                "address_1": "123 Main Street",
                "address_2": "Suite 200",
                "city": "Washington",
                "state": "DC",
                "zipcode": "20036",
                "interests": ["product_1", "product_4", "product_7"],
                "contact_requested": True,
                "created_at": datetime.datetime.utcnow(),
                "updated_at": datetime.datetime.utcnow()}
customer_id = customers.insert_one(new_customer).inserted_id
print(customer_id)

How it works…

The method insert_one() allows us to insert a single document. If you need to use that record immediately after it's inserted, be sure to return the customer_id of the new record as we have done in this recipe.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset