Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Python MongoDB - distinct()
Next article icon

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
importpymongoclient=pymongo.MongoClient("mongodb://localhost:27017/")# Database Namedb=client["database"]# Collection Namecol=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
importpymongoclient=pymongo.MongoClient("mongodb://localhost:27017/")# Database Namedb=client["database"]# Collection Namecol=db["GeeksForGeeks"]x=col.find()fordatainx:print(data)

Output: 

find_one() andfind() 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
importpymongoclient=pymongo.MongoClient("mongodb://localhost:27017/")# Database Namedb=client["database"]# Collection Namecol=db["GeeksForGeeks"]# Fields with values as 1 will# only appear in the resultx=col.find({},{'_id':0,'appliance':1,'rating':1,'company':1})fordatainx:print(data)

Output: 


Improve
Article Tags :
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp