Python - Read data from MongoDB - onlinetutorialspoint

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
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.
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()
The pymongo provides two methods to read databases: find_one() and find().
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.
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.
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'}

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_namewith 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.
PyMongo collections
MongoDB Query
Insert data into MongoDB
Happy Learning 🙂

Python – Update MongoDB documents
Python – Delete MongoDB Documents
Python – Create MongoDB Database and Inserting Documents
How to Connect MongoDB with Python
Python read data from MySQL Database
Python raw_input read input from keyboard
Python How to read input from keyboard
What are different Python Data Types
Python List Data Structure In Depth
Python Tuple Data Structure in Depth
Python – How to Read Google Search Results in Selenium
How to Read CSV File in Python
How to read a text file in Python ?
How to read JSON file in Python ?
Python – How to read environment variables ?

Python – Update MongoDB documents
Python – Delete MongoDB Documents
Python – Create MongoDB Database and Inserting Documents
How to Connect MongoDB with Python
Python read data from MySQL Database
Python raw_input read input from keyboard
Python How to read input from keyboard
What are different Python Data Types
Python List Data Structure In Depth
Python Tuple Data Structure in Depth
Python – How to Read Google Search Results in Selenium
How to Read CSV File in Python
How to read a text file in Python ?
How to read JSON file in Python ?
Python – How to read environment variables ?
 


Δ
 Python – Introduction
 Python – Features
 Python – Install on Windows
 Python – Modes of Program
 Python – Number System
 Python – Identifiers
 Python – Operators
 Python – Ternary Operator
 Python – Command Line Arguments
 Python – Keywords
 Python – Data Types
 Python – Upgrade Python PIP
 Python – Virtual Environment
 Pyhton – Type Casting
 Python – String to Int
 Python – Conditional Statements
 Python – if statement
 Python – *args and **kwargs
 Python – Date Formatting
 Python – Read input from keyboard
 Python – raw_input
 Python – List In Depth
 Python – List Comprehension
 Python – Set in Depth
 Python – Dictionary in Depth
 Python – Tuple in Depth
 Python – Stack Datastructure
 Python – Classes and Objects
 Python – Constructors
 Python – Object Introspection
 Python – Inheritance
 Python – Decorators
 Python – Serialization with Pickle
 Python – Exceptions Handling
 Python – User defined Exceptions
 Python – Multiprocessing
 Python – Default function parameters
 Python – Lambdas Functions
 Python – NumPy Library
 Python – MySQL Connector
 Python – MySQL Create Database
 Python – MySQL Read Data
 Python – MySQL Insert Data
 Python – MySQL Update Records
 Python – MySQL Delete Records
 Python – String Case Conversion
 Howto – Find biggest of 2 numbers
 Howto – Remove duplicates from List
 Howto – Convert any Number to Binary
 Howto  – Merge two Lists
 Howto – Merge two dicts
 Howto – Get Characters Count in a File
 Howto – Get Words Count in a File
 Howto – Remove Spaces from String
 Howto –  Read Env variables
 Howto – Read a text File
 Howto – Read a JSON File
 Howto –  Read Config.ini files
 Howto – Iterate Dictionary
 Howto – Convert List Of Objects to CSV
 Howto – Merge two dict in Python
 Howto – create Zip File
 Howto – Get OS info
 Howto – Get size of Directory
 Howto – Check whether a file exists
 Howto –  Remove key from dictionary
 Howto – Sort Objects
 Howto – Create or Delete Directories
 Howto – Read CSV File
 Howto – Create Python Iterable class
 Howto – Access for loop index
 Howto – Clear all elements from List
 Howto – Remove empty lists from a List
 Howto – Remove special characters from String
 Howto – Sort dictionary by key
 Howto – Filter a list