Innovate anywhere, anytime withruncode.io Your cloud-based dev studio.
MongoDB

MongoDB CRUD Operations with Python (Pymongo)

2022-07-21

PyMongo is a Python distribution  that contains tools for working with MongoDB, So in this blog post let’s see some basic methods that perform CRUD operations to a collection.

Install pymongo:

pip install pymongo

Connecting  to with Database with PyMongo:

  1. To perform CRUD operations first need to establish the connection using Mongo client 
>>> from pymongo import MongoClient
>>> client = MongoClient('localhost',27017)  # 27017 is the default port number for mongodb

2. Next step is to connect to the database (test).

db = client.test

3. Now retrieve the collection (person) from the database

col = db.person

Now we are ready to perform the actual CRUD operations.

CRUD Operations:

C-Create: 

Mongo store the data in the form of JSON objects. So every record for a collection in mongo is called a document. If the collection does not currently exist, insert operations will create the collection. We can insert the documents into collection in 3 ways.

  • insert_one()
  • insert_many()
  • insert()
  1. insert_one(): insert_one() inserts a single document into a collection.
col.insert_one(
   {
      name: "John",
      salary: 100 ,
   }
)

The above snippet returns the pymongo.results.InsertOneResult object:

<pymongo.results.InsertOneResult object at 0x7f8fbe7fb960>

2. insert_many(): insert_many() inserts multiple documents into a collection.

The following example inserts three new documents into the users collection. Each document has two fields name and salary. Since the documents do not specify an _id field, MongoDB adds the _id field with an ObjectId value to each document.

col.insert_many(
   [
     { name: "Jeorge", salary: 100},
     { name: "Steve", salary: 100},
     { name: "David", salary: 100}
   ]
)

The method returns a pymongo.results.InsertManyResult object

<pymongo.results.InsertManyResult object at 0x7f8fbe7fb7d0>

3. insert(): insert() can be used to insert single or array or documents.

# single document
col.insert({ name: "Jeorge", salary: 100})

# array of documents
col.insert([{ name: "Jeorge", salary: 100}, { name: "Steve", salary: 100}])

insert() method returns all the Object ids of the documents that are inserted.

# return type of single document
ObjectId('57611d4b1aa303032ad5ba9e')

# return type of multiple documents
[ObjectId('57611d4b1aa303032ad5ba9e'), ObjectId('57611d4b1aa30303sdd5ba9e')]

R-Read:

We can retrieve the documents from a collection using 2 methods.

  • find()
  • find_one()
  1. find(): find() function will return with all the documents in that collection. By default it returns a cursor object.
col.find()
<pymongo.cursor.Cursor object at 0x7f8fc1853890>

2. find_one(): find_one() returns the first document in the collection.

col.find_one()
{u'salary': 100, u'_id': ObjectId('57611a711aa303032ad5ba9b'), u'name': u'John'}

We can filter the results by applying conditions on these methods as following

col.find_one({"name": "John"}) # returns object.
col.find({"name": "John"}) # returns cursor

U- Update:

We can update the documents from the collection with the following methods.

  • update()
  • update_one()
  • update_many()
  • replace_one()

The general syntax for all the above methods is

<method_name>(condition, update_or_replace_document, upsert=False, bypass_document_validation=False)

Here 

condition: A query that matches the document to replace.
update_or_replace_document: The new document.
upsert (optional): If True, perform an insert if no documents match the filter.
bypass_document_validation: (optional) If True, allows the write to opt-out of document level validation. Default is False.

Following are the snippets forh update(), update_one(), update_many() and replace_one(). All the methods will return UpdateResult object except update().

# update_one
>>> col.update_one({"name":"John"}, {"$set":{"name":"Joseph"}})
<pymongo.results.UpdateResult object at 0x7f8fbe7fb910>

# update_many
>>> col.update_many({"name":"John"}, {"$set":{"name":"Joseph"}})
<pymongo.results.UpdateResult object at 0x7f8fbe7fb7d0>

# update
>>> col.update({"name":"John"}, {"$set":{"name":"Jeorge"}})
{'updatedExisting': False, u'nModified': 0, u'ok': 1, u'n': 0}

#replace_one
>>> col.replace_one({"name":"John"}, {"name":"Jeorge"})
<pymongo.results.UpdateResult object at 0x7f8fbe7fb910>

D- Delete:

We can delete the documents in the collection using  the following methods.

  • delete_one()
  • delete_many()

Both these methods will return a DeleteResult object. The general syntax for the above methods is as follows.

<method_name>(condition)

Following are the examples how we use the delete_one() and delete_many() methods, both returns the DeleteResult object.

>>> col.delete_one({"name":"John"})
<pymongo.results.DeleteResult object at 0x7f8fbe7fba00>

>>> col.delete_many({"name":"John"})
<pymongo.results.DeleteResult object at 0x7f8fbe7fb960>