Insert documents with Pymongo

In this example we are going to see what steps are necessary to insert a document into MongoDB using Pymongo. To insert documents with Pymongo, the first thing we will have to do is import the library.

from pymongo import MongoClient

Specifically the MongoClient object, which is what will allow us to access the MongoDB.

Using the client we must select the database and collection in which we are going to insert documents with pymongo.

db = client.test
users = db.users

In this case we have used the test database and the users collection. We see that Pymongo’s notation is the same as if we were writing in the MongoDB.

We could even have limited it by writing.

users = client.test.users

Now we are going to prepare the JSON document that we are going to insert. We define the document directly.

user = {
    'name': 'Victor',
    'age': 38,
    'locality': 'Avila'
}

The only thing you have to be careful with is that the document properties are put with single quotes.

Now we move on to insert the document, to do this we rely on the .insert_one() method, which will receive the document that we had defined as a parameter.

result = users.insert_one(user)

We see that we leave the result in the variable result. The insert_one() method returns an InsertOneResult object which contains an attribute called inserted_id which is the identifier of the inserted object.

So we can display this identifier to validate the insertion operation.

print 'Inserted object ' + str(result.inserted_id)

This id corresponds to the ObjectId of the object inserted in the MongoDB database.

Simple steps that allow us to insert documents with Pymongo.