![]() |
VOOZH | about |
The findOne() method fetches a single matching document from a MongoDB collection, making it ideal when only one specific result is needed.
db.collection.findOne(query, projection)Here are a few practical examples using the student collection:
[
{ "_id": ObjectId("6011c71f781ba1a1c1ffc5b1"), "name": "Nicol", "language": "C++" },
{ "_id": ObjectId("6011c71f781ba1a1c1ffc5b2"), "name": "Alen", "language": "python" },
{ "_id": ObjectId("6011c71f781ba1a1c1ffc5b3"), "name": "Tim", "language": "python" }
]
Retrieve a single document from the student collection.
Query:
db.student.findOne({})Output:
{ "_id": ObjectId("6011c71f781ba1a1c1ffc5b1"), "name": "Nicol", "language": "C++" }Retrieve a document where the name is "Alen".
Query:
db.student.findOne({ name: "Alen" })Output:
{ "_id": ObjectId("6011c71f781ba1a1c1ffc5b2"), "name": "Alen", "language": "python" }Retrieve a document where the name is Tim and return only the name and language fields.
Query:
db.student.findOne({ name: "Tim" }, { _id: 0, name: 1, language: 1 })Output:
{ "name": "Tim", "language": "python" }Retrieve a document where the name is "Nicol" and return all fields except the _id field.
Query:
db.student.findOne({ name: "Nicol" }, { _id: 0 })Output:
{ "name": "Nicol", "language": "C++" }Retrieve a document where the language is "python". If no document matches the criteria, findOne() returns null.
Query:
var result = db.student.findOne({ language: "python" });
print(result);
Output:
{ "_id": ObjectId("6011c71f781ba1a1c1ffc5b2"), "name": "Alen", "language": "python" }