Inserting multiple records using PyMongo

Many applications need to support the bulk importing of records. PyMongo makes this easy with the insert_many() method.

Getting ready

In order to insert multiple records, we need to first create a list of documents to insert, and then compile them into a single python list.

How to do it…

from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.pythonbicookbook
customers = db.customers
new_customers = [{"first_name": "Jane",
                    "last_name": "Doe",
                    "address_1": "123 12th Street NW",
                    "address_2": "Suite 1200",
                    "city": "Washington",
                "state": "DC",
                "zipcode": "20036",
                "interests": ["product_2", "product_3", "product_8"],
                "contact_requested": False,
                "created_at": datetime.datetime.utcnow(),
                "updated_at": datetime.datetime.utcnow()},
                 {"first_name": "Jordan",
                    "last_name": "Belfry",
                    "address_1": "19340 17th Street SE",
                    "address_2": "Suite 50",
                    "city": "Washington",
                "state": "DC",
                "zipcode": "20034",
                "interests": ["product_1", "product_2", "product_3"],
                "contact_requested": False,
                "created_at": datetime.datetime.utcnow(),
                "updated_at": datetime.datetime.utcnow()}]
new_customer_ids = customers.insert_many(new_customers)
print(new_customer_ids.inserted_ids)

How it works…

By default, insert_many() inserts the documents in an arbitrary order, and if an error occurs, it will try to insert the rest of the records. If you set ordered=True, PyMongo will attempt to insert the documents serially. However, if an error occurs, the insert will be aborted.

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

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