How to connect with MongoDB Database in Python

In the previous article, we discuss on how to connect with MySQL database in Python, in this article we will see how to connect MongoDB database with Python.

MongoDB is open-source and json based NoSQL database management system. MongoDB store all data in collection with key and value. To connect MongoDB database with Python, you will need to install MongoDB driver to access MongoDB database.

We will install PyMongo driver with PIP command. It is easy and recommend you install python packages with PIP.

To install PyMongo driver, run the below command in Terminal.

python3 -m pip install pymongo

Now you can use PyMongo package for interacting with MongoDB database.

Create database

import pymongo

client = pymongo.MongoClient("localhost", 27017)

db = client.testdb

To get all list of system database:

print(client.list_database_names())

To check if database already exist

dbname = client.list_database_names()
if "mydatabase" in dbname:
    print("The database exists.")

Create and insert collection

Collection is same as table in MySQL. Here’s a basic example for creating collection.

db.my_collection
Collection(Database(MongoClient('localhost', 27017), u'test'), u'my_collection')
db.my_collection.insert_one({"name": "hackthestuff"}).inserted_id
# 5b1910482ddb101b7042fcd7

To insert multiple collection, you may use insert_many() method:

import pymongo

client = pymongo.MongoClient("localhost", 27017)
mydb = client["my_database"]
myrec = mydb["users"]

mylist = [
    { "name": "HacktheStuff"},
    { "name": "Laravelcode"},
    { "name": "ITSolution_stuff"}
]

x = myrec.insert_many(mylist)

# print list of the _id values of the inserted documents:
print(x.inserted_ids)

MongoDB Query

To search records in MongoDB, find() method is used. This will filter the search results.

import pymongo

client = pymongo.MongoClient("localhost", 27017)
mydb = client["my_database"]
myrec = mydb["users"]

myquery = {"name": "Laravelcode"}

results = myrec.find(myquery)

for x in results:
    print(x)

If you only want to get first result, use find_one() method instead of find()method.

import pymongo

client = pymongo.MongoClient("localhost", 27017)
mydb = client["my_database"]
myrec = mydb["users"]

myquery = {"name": "Laravelcode"}

results = myrec.find_one(myquery)

print(results)

sort() method will sort the result into specific collection. The second parameter in sort() method will sort by ascending(1) or descending(-1) order.

import pymongo

client = pymongo.MongoClient("localhost", 27017)
mydb = client["my_database"]
myrec = mydb["users"]

myquery = {"name": "Laravelcode"}

results = myrec.find(myquery).sort("name", -1)

for x in results:
    print(x)

limit() method will return limited number of rows.

import pymongo

client = pymongo.MongoClient("localhost", 27017)
mydb = client["my_database"]
myrec = mydb["users"]

myquery = {"name": "Laravelcode"}

results = myrec.find(myquery).limit(2)

for x in results:
    print(x)

Update records

To update records, you can update records using update_one() or update_many() method.

Update only first result using update_one() method.

import pymongo

client = pymongo.MongoClient("localhost", 27017)
mydb = client["my_database"]
myrec = mydb["users"]

myquery = {"name": "Laravelcode"}
newquery = {"$set": { "name": "Laravel-News" }}

myrec.update_one(myquery, newquery)

Update all searched records using update_many() method.

import pymongo

client = pymongo.MongoClient("localhost", 27017)
mydb = client["my_database"]
myrec = mydb["users"]

myquery = {"name": {"$regex": "^Laravel"}}
newquery = {"$set": { "name": "Laravel-News" }}

myrec.update_many(myquery, newquery)

Delete records

In the same way, you can delete records using delete_one() or delete_many() method.

import pymongo

client = pymongo.MongoClient("localhost", 27017)
mydb = client["my_database"]
myrec = mydb["users"]

myquery = {"name": "Laravelcode"}

myrec.delete_one(myquery)

Drop collection

To drop whole collection, use drop() method.

import pymongo

client = pymongo.MongoClient("localhost", 27017)
mydb = client["my_database"]
myrec = mydb["users"]

myrec.drop()

This will return true if collection dropped successfully. If there is no collection, it will return false.

This way, you can connect and work with MongoDB Database in Python.

Tags:

Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

Or

No Comment