So far, we have set up everything now time to read data from the MongoDB database. In the previous tutorial, we created a database and inserted documents using different methods.
Python Read data from MongoDB:
Insert some data into the database before reading it, and I just copied the below snipped from the previous tutorial.
from pymongo import MongoClient
mclient = MongoClient('localhost', 27017)
db = mclient['Newdatabase']
mcol = db["Employers"]
mlist = [
{ "_id": 1, "f_name": "Nil", "l_name": "Mil" },
{ "_id": 2, "f_name": "Andy", "l_name": "Apple" },
{ "_id": 3, "f_name": "AMad", "l_name": "Amhed" },
]
mid = mcol.insert_many(mlist)
print(mid.inserted_ids)
mclient.close()
Read MongoDB database with Python:
The pymongo
provides two methods to read databases: find_one()
and find()
.
Using find_one():
find_one()
works as SELECT
from MYSQL but only returns the first occurrence in the selection.
The find_one() is an overloaded function to pass the optional query as an argument to filter the data or read selected columns.
If no matches are found, this function returns blank, and if the query matches multiple data, it returns the very first document in the collection.
Run:
from pymongo import MongoClient
mclient = MongoClient('localhost', 27017)
db = mclient['Newdatabase']
mcol = db["Employers"]
mrd= mcol.find_one()
print(mrd)
mclient.close()
Output:
{'_id': ObjectId('6197f62a5312dd9e82102c6b'), 'f_name': 'Rob', 'l_name': 'Carpenter'}
Check the insert_one()
section of the previous tutorial, and you’ll realize the result is correct.
Using find():
If you want to read all the data from a collection, you can use the find() function. It takes two optional parameters. The first is a query, and the second is projections (the columns you want to read). If the find()
function has no parameters, it returns the same result as SELECT *
in MySQL without anywhere condition.
In other words, find() without argument returns all documents of collection in the database.
from pymongo import MongoClient
mclient = MongoClient('localhost', 27017)
db = mclient['Newdatabase']
mcol = db["Employers"]
for mrd in mcol.find():
print(mrd)
mclient.close()
Output:
{'_id': ObjectId('6197f62a5312dd9e82102c6b'), 'f_name': 'Rob', 'l_name': 'Carpenter'}
{'_id': ObjectId('6197f7eb588c1566078fbff2'), 'f_name': 'Rob', 'l_name': 'Carpenter'}
{'_id': ObjectId('619800106f7cca5b81de7ec7'), 'f_name': 'Nil', 'l_name': 'Mil'}
{'_id': ObjectId('619800106f7cca5b81de7ec8'), 'f_name': 'Andy', 'l_name': 'Apple'}
{'_id': ObjectId('619800106f7cca5b81de7ec9'), 'f_name': 'AMad', 'l_name': 'Amhed'}
{'_id': 1, 'f_name': 'Nil', 'l_name': 'Mil'}
{'_id': 2, 'f_name': 'Andy', 'l_name': 'Apple'}
{'_id': 3, 'f_name': 'AMad', 'l_name': 'Amhed'}
As seen in the output, find()
returns all the documents from the collection.
MongoDB find() with Projections:
Projections allow us to read specific columns from a collection. As discussed earlier, the find() function is an overloaded function that takes two optional parameters.
To apply the projection to the query, we must pass the required column list as a second parameter like({}, { "_id" :0, "f_name": 1,})
an argument. In the example, we are only projecting the f_name column from the collection. Here 0
means to ignore and 1
means select.
Example:
from pymongo import MongoClient
mclient = MongoClient('localhost', 27017)
db = mclient['Newdatabase']
mcol = db["Employers"]
for mrd in mcol.find({}, { "_id" :0, "f_name": 1,}):
print(mrd)
mclient.close()
The above-given parameter selects only the first name.
Output:
{'f_name': 'Rob'}
{'f_name': 'Rob'}
{'f_name': 'Nil'}
{'f_name': 'Andy'}
{'f_name': 'AMad'}
{'f_name': 'Nil'}
{'f_name': 'Andy'}
{'f_name': 'AMad'}
MongoDB find() with conditions:
The conditional query is similar to where
in MYSQL.
Let’s use conditional query to find documents whose f_name
is 'Nil
.
Run:
from pymongo import MongoClient
mclient = MongoClient('localhost', 27017)
db = mclient['Newdatabase']
mcol = db["Employers"]
mquery = { "f_name": "Nil" }
nval = mcol.find(mquery)
for mrd in nval:
print(mrd)
mclient.close()
Output:
{'_id': ObjectId('619d4553c0d6415b4736864d'), 'f_name': 'Nil', 'l_name': 'Mil'}
{'_id': 1, 'f_name': 'Nil', 'l_name': 'Mil'}
As expected, documents with f_name
with value 'Nil'
is returned.
Use the greater than modifier to discover documents where the f name
field begins with the letter N
or above (alphabetically). The $gt
used to do the same.
from pymongo import MongoClient
mclient = MongoClient('localhost', 27017)
db = mclient['Newdatabase']
mcol = db["Employers"]
mquery = { "f_name": { "$gt": "N" } }
nval = mcol.find(mquery)
for mrd in nval:
print(mrd)
mclient.close()
Output:
{'_id': ObjectId('619d4553c0d6415b4736864d'), 'f_name': 'Nil', 'l_name': 'Mil'}
{'_id': 1, 'f_name': 'Nil', 'l_name': 'Mil'}
As expected, documents with f_name
'Nil'
is obtained.
We can also use regex as a modifier to query string. Let’s find documents where the l_name
starts with the letter 'M'
.
Run:
from pymongo import MongoClient
mclient = MongoClient('localhost', 27017)
db = mclient['Newdatabase']
mcol = db["Employers"]
mquery = { "l_name": { "$regex": "M" } }
nval = mcol.find(mquery)
for mrd in nval:
print(mrd)
mclient.close()
Output:
{'_id': ObjectId('619d4553c0d6415b4736864d'), 'f_name': 'Nil', 'l_name': 'Mil'}
{'_id': 1, 'f_name': 'Nil', 'l_name': 'Mil'}
As expected, documents with l_name
that starts from 'M'
is obtained. Check out the reference to see more modifier and their usage.
References:
Happy Learning 🙂