MongoDB CRUD operations with Python (Pymongo)

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. insert_one(), insert_many(), find_one(), find(), update(), delete(), ...

I, Connect and Create Database

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["mytable"]

II, Create, Write

1, insert()

can be used to insert 1 or more records.

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["users"]

# insert single user
mycol.insert({ "username": "aaa", "pass": "123456" })

# insert many users
mycol.insert([{ "username": "bbb", "pass": "123456" }, { "username": "ccc", "pass": "123456" }])

insert() method returns

# insert single user
ObjectId('5fbe1c17242098c02a7f4ecb')

# insert many users
[ObjectId('5fbe1c17242098c02a7f4ecb'), ObjectId('5fbe1c63fa9741631f6a1f6c')]

2, insert_one()

inserts a single record into a DB

mycol.insert_one({ "username": "aaa", "pass": "123456" })

3, insert_many()

inserts multiple record into a collection

mycol.insert_many([
    { "username": "aaa", "pass": "123456" },
    { "username": "bbb", "pass": "123456" },
    { "username": "ccc", "pass": "123456" }
])

III, Update

1, update()

myquery = { "username": "aaa" }
newvalues = { "$set": { "username": "ddd" } }

mycol.update(myquery, newvalues)

2, update_one()

myquery = { "username": "aaa" }
newvalues = { "$set": { "username": "ddd" } }

mycol.update_one(myquery, newvalues)

3, update_many()

myquery = { "username": "aaa" }
newvalues = { "$set": { "username": "ddd" } }

mycol.update_many(myquery, newvalues)

4, replace_one()

myquery = { "username": "aaa" }
newvalues = { "username": "ddd" }

mycol.replace_one(myquery, newvalues)

IV, Select data, Read, Find, Search, Sort

1, find()

returns all records

mycol.find()
# return
<pymongo.cursor.Cursor object at 0x7f8fc1878890>

2, find_one()

return first record

mycol.find_one()

# return 
{'id': ObjectId('5fbe1c17242098c02a7f4ecb'), 'username': 'aaa',  'pass': '123456'}

3, Filter

myquery = { "username": "aaa" } 
mydoc = mycol.find(myquery)

for x in mydoc:
  print(x)

find all records whose username starts with 'a'

myquery = { "username": { "$gt": "a" } }
mydoc = mycol.find(myquery)

for x in mydoc:
  print(x)

4, Sort

ASC

mydoc = mycol.find().sort("username", 1)

DESC

mydoc = mycol.find().sort("username", -1)

5, limit

users = mycol.find().limit(5)

V, Delete

1, delete_one()

mycol.delete_one({ "username": "aaa" })

2, delete_many()

mycol.delete_many({ "username": "aaa" })