How to Use findOne in MongoDB: Syntax and Examples
In MongoDB, use
findOne() to retrieve the first document that matches a query filter from a collection. It returns a single document or null if no match is found. You can specify a filter object and optionally a projection to control which fields are returned.Syntax
The findOne() method is called on a MongoDB collection. It takes two optional arguments: a filter object to specify the search criteria, and an options object to specify additional options such as projection.
filter: Defines the conditions documents must meet to be returned.options: Defines additional options likeprojectionto specify which fields to return (1 to include, 0 to exclude).
If no filter is provided, findOne() returns the first document in the collection.
javascript
db.collection.findOne(filter, options)
Example
This example shows how to find one document in the users collection where the name is "Alice". It also demonstrates how to return only the name and email fields.
javascript
const { MongoClient } = require('mongodb'); async function run() { const client = new MongoClient('mongodb://localhost:27017'); try { await client.connect(); const db = client.db('testdb'); const users = db.collection('users'); // Find one user named Alice const user = await users.findOne( { name: 'Alice' }, { projection: { name: 1, email: 1, _id: 0 } } ); console.log(user); } finally { await client.close(); } } run().catch(console.dir);
Output
{"name":"Alice","email":"alice@example.com"}
Common Pitfalls
Common mistakes when using findOne() include:
- Not awaiting the asynchronous call in Node.js, which results in a Promise instead of the document.
- Using incorrect filter syntax, causing no documents to match.
- Expecting multiple documents but
findOne()returns only one. - Not specifying projection correctly, which may return unwanted fields like
_id.
javascript
/* Wrong: missing await, returns a Promise */ const user = users.findOne({ name: 'Alice' }); /* Right: await the Promise to get the document */ const user = await users.findOne({ name: 'Alice' });
Quick Reference
| Parameter | Description | Example |
|---|---|---|
| filter | Object to specify search criteria | { name: 'Alice' } |
| options | Additional options like projection | { projection: { name: 1, email: 1 } } |
| Return value | Single document or null if none found | {"name":"Alice","email":"alice@example.com"} |
Key Takeaways
Use findOne() to get the first matching document from a MongoDB collection.
Always await findOne() in asynchronous code to get the actual document.
Provide a filter object to specify search criteria; omit to get the first document.
Use projection to control which fields are returned, excluding _id if desired.
Remember findOne() returns only one document, not multiple.