find_one Example
This page was last reviewed on 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://") 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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
© 2007-2024 Sam Allen.