0
0
MongoDBquery~5 mins

findOne method in MongoDB

Choose your learning style9 modes available
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.

You want to get details of a single user by their username.
You need to find one product by its ID to show on a page.
You want to check if a specific email exists in your database.
You want to retrieve one order record to update its status.
You want to find one document that matches a condition without loading many results.
Syntax
MongoDB
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).

Examples
Find one user whose username is 'alice'.
MongoDB
db.users.findOne({ username: "alice" })
Find one product with price less than 20.
MongoDB
db.products.findOne({ price: { $lt: 20 } })
Find one pending order and only show the orderId field.
MongoDB
db.orders.findOne({ status: "pending" }, { projection: { _id: 0, orderId: 1 } })
Sample Program

This example switches to the shopDB database and finds one user named 'John' from the users collection.

MongoDB
use shopDB

// Find one user with name 'John'
db.users.findOne({ name: "John" })
OutputSuccess
Important Notes

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.

Summary

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.