Skip to content
Related Articles

Related Articles

How to fetch data from MongoDB using Python?

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 04 Jul, 2022
Improve Article
Save Article

MongoDB is a cross-platform, document-oriented database that works on the concept of collections and documents. MongoDB offers high speed, high availability, and high scalability.

Fetching data from MongoDB

Pymongo provides various methods for fetching the data from mongodb. Let’s see them one by one.

1) Find One: This method is used to fetch data from collection in mongoDB. It returns first first occurrence. 
Syntax :

find_one()

Example:

Sample Database:

python-mongodb-sample-data

Python3




import pymongo
 
 
client = pymongo.MongoClient("mongodb://localhost:27017/")
 
# Database Name
db = client["database"]
 
# Collection Name
col = db["GeeksForGeeks"]
 
x = col.find_one()
 
print(x)


Output :

2) Find All: For all occurrences in the selection, use find() method. It works like Select * query  of SQL. 

Syntax

find()

Example:

Python3




import pymongo
 
 
client = pymongo.MongoClient("mongodb://localhost:27017/")
 
# Database Name
db = client["database"]
 
# Collection Name
col = db["GeeksForGeeks"]
 
x = col.find()
 
for data in x:
    print(data)


Output: 

find_one() and find() accepts an optional filter parameter that selects which documents to include in the result set. Can be an empty document to include all documents. 
3) Fetching only specific fields: If you want to fetch only some fields then in the find method pass the first parameter as {} and second parameter as 1 for those field that you want to fetch and 0 for those you don’t want to fetch. 
Syntax: 

find({},{field_data:bool})

Example: 

Python3




import pymongo
 
 
client = pymongo.MongoClient("mongodb://localhost:27017/")
 
# Database Name
db = client["database"]
 
# Collection Name
col = db["GeeksForGeeks"]
 
# Fields with values as 1 will
# only appear in the result
x = col.find({},{'_id': 0, 'appliance': 1,
                 'rating': 1, 'company': 1})
 
for data in x:
    print(data)


Output: 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!