Find_one
, MongoDBOften 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.
Consider this example program. We reset the "categories" collection in a "content" database. We add 3 documents, each with a language key.
find_one
.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
None
Our database does not include an entry matching "Fortran." So the None
value is returned. We can test None
directly in Python.
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.