Introduction
The findOne method helps you quickly get one matching item from a collection. It is simple and fast when you only need a single result.
Jump into concepts and practice - no test required
The findOne method helps you quickly get one matching item from a collection. It is simple and fast when you only need a single result.
db.collection.findOne(filter, options)
filter is how you tell MongoDB what to look for.
options can control which fields to show or other settings (optional).
db.users.findOne({ username: "alice" })db.products.findOne({ price: { $lt: 20 } })db.orders.findOne({ status: "pending" }, { projection: { _id: 0, orderId: 1 } })This example switches to the shopDB database and finds one user named 'John' from the users collection.
use shopDB // Find one user with name 'John' db.users.findOne({ name: "John" })
If multiple documents match, findOne returns the first one it finds.
You can use projection in options to limit which fields are returned.
If no document matches, findOne returns null.
findOne gets a single matching document from a collection.
Use a filter to specify what you want to find.
It returns null if nothing matches.
findOne method do in MongoDB?findOnefindOne method is designed to find a single document that matches the filter criteria in a MongoDB collection.findOne only retrieves one matching document without changing the data.findOne = single matching document [OK]name equal to 'Alice' using findOne?{name: 'Alice'}.db.collection.findOne({name: 'Alice'}). Other options use invalid operators or syntax.users with documents: {name: 'Bob', age: 30}, {name: 'Alice', age: 25}, {name: 'Bob', age: 22}db.users.findOne({name: 'Bob'}) return?findOne method returns the first document matching the filter in the collection's natural order.name: 'Bob' is {name: 'Bob', age: 30}.db.users.findOne(name: 'Alice'){name: 'Alice'}.email 'user@example.com' but only want to return the name and age fields. Which findOne query is correct?findOne is the projection object that specifies which fields to include (1) or exclude (0).name and age and exclude _id, use {name: 1, age: 1, _id: 0}. db.users.findOne({email: 'user@example.com'}, {name: 1, age: 1, _id: 0}) matches this.