How to fetch data from MongoDB using Python?

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 varoius 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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output :
 

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

Syntax :



find()

Example :

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

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)

chevron_right


Output: 
 

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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)

chevron_right


Output: 

 

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.