Home
MongoDB
find_one Example
Updated Oct 11, 2023
Dot Net Perls
Find_one, MongoDB. Often just a single match is needed in a MongoDB query. The find_one method is ideal here. It returns the values found, or None if nothing matches.
With None, we can test the database to ensure a document is not present. This helps us avoid conflicts. Find_one is easy to use once the MongoDB is ready.
An example. Consider this example program. We reset the "categories" collection in a "content" database. We add 3 documents, each with a language key.
And We set the status one each document as well. This can be retrieved from the result of find_one.
Detail We invoke find_one on the categories collection. One match for "Java" is returned.
from pymongo import MongoClient

client = MongoClient("mongodb://127.0.0.1:27017")
db = client.content

# Reset.
db.categories.delete_many({})

# Insert some documents.
db.categories.insert_many([
    {"language": "C#", "status": 1},
    {"language": "Java", "status": 1},
    {"language": "Python", "status": 2},
])

# Find a matching document.
print("FIND ONE JAVA")
result = db.categories.find_one({"language": "Java"})
print(result)
# Access the status key.
print("STATUS")
print(result["status"])

# This query matches no documents.
print("FIND ONE FORTRAN")
result = db.categories.find_one({"language": "Fortran"})
print(result)
if result == None:
    print("NOT FOUND")
FIND ONE JAVA {'status': 1, 'language': 'Java', '_id': ObjectId('59efce1a25149714a00cf82d')} STATUS 1 FIND ONE FORTRAN None NOT FOUND
Notes, None. Our database does not include an entry matching "Fortran." So the None value is returned. We can test None directly in Python.
A summary. With the return value of find_one, we can access individual keys and values (like in a Python dictionary). The syntax of MongoDB here is clear.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
No updates found for this page.
Home
Changes
© 2007-2025 Sam Allen