Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Python MongoDB - find_one_and_update Query
Next article icon

In PyMongo, thefind_one()method is used to retrieve a single document from a MongoDB collection that matches the given filter. If multiple documents match, only the first match (based on insertion order) is returned.

Syntax

collection.find_one(filter, projection=None)

Parameters:

Here is our sample data.

Python
frompymongoimportMongoClientc=MongoClient("mongodb://localhost:27017/")db=c['userDB']col=db['users']data=[{"_id":1,"name":"Amit","age":25,"city":"Delhi"},{"_id":2,"name":"Drew","age":30,"city":"Mumbai"},{"_id":3,"name":"Cody","age":28,"city":"Chennai"}]col.delete_many({})col.insert_many(data)print("Data inserted.")

Output

Sample_data
Sample data

Explanation:

  • MongoClient() connects to the local MongoDB server and selects the userDB.users collection.
  • delete_many({})clears any existing documents in the collection to avoid duplicate entries.
  • insert_many(data) loads the sample user documents into the users collection.

Examples

Example 1:Find by name

Python
frompymongoimportMongoClientc=MongoClient("mongodb://localhost:27017/")db=c['userDB']col=db['users']res=col.find_one({"name":"Amit"})print(res)

Output

Output

Explanation:Finds the first document where name is "Amit".

Example 2:find_one andexclude _id field

Python
frompymongoimportMongoClientc=MongoClient("mongodb://localhost:27017/")db=c['userDB']col=db['users']res=col.find_one({"name":"Drew"},{"_id":0})print(res)

Output

Output
Output in Terminal

Explanation:Finds the document where name is "Drew" and excludes the _id field from the result using projection.

Example 3: Find by "age" condition

Python
frompymongoimportMongoClientc=MongoClient("mongodb://localhost:27017/")db=c['userDB']col=db['users']res=col.find_one({"age":{"$gt":26}})print(res)

Output

Outputbgyju
Output in Terminal

Explanation: Finds the first document where age is greater than 26 using the$gt (greater than) operator.

Related Articles


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