Open In App

How to Find Documents by ID in MongoDB?

In MongoDB, finding documents by their unique identifier (ID) is a fundamental operation that allows us to retrieve specific records efficiently. Each document in a MongoDB collection has a unique _id field, which serves as the primary key.

In this article, we will explore how to find documents by ID in MongoDB by covering concepts, and examples in detail to understand the process effectively.



Understanding MongoDB IDs

Types of _id Values

Examples of How to Find Documents by ID in MongoDB?

Let’s set up an Environment:

To understand How to Find Documents by ID in MongoDB we need a collection and some documents on which we will perform various operations and queries. Here we will consider a collection called users which contains the information shown below:



[
{
_id: ObjectId('6626039e9fe21c773b8bf207'),
name: 'Alice',
age: 30,
email: 'alice@example.com'
},
{
_id: ObjectId('6626039e9fe21c773b8bf208'),
name: 'Bob',
age: 25,
email: 'bob@example.com'
},
{
_id: ObjectId('6626039e9fe21c773b8bf209'),
name: 'Charlie',
age: 35,
email: 'charlie@example.com'
},
{
_id: ObjectId('6626039e9fe21c773b8bf20a'),
name: 'David',
age: 40,
email: 'david@example.com'
},
{
_id: ObjectId('6626039e9fe21c773b8bf20b'),
name: 'Eve',
age: 28,
email: 'eve@example.com'
}
]

Example 1

To find a user by their _id, use the following query in the MongoDB shell

// Finding a document by _id using findOne()
db.users.findOne({ "_id": ObjectId("6626039e9fe21c773b8bf207") });

Output:

{
_id: ObjectId('6626039e9fe21c773b8bf207'),
name: 'Alice',
age: 30,
email: 'alice@example.com'
}

Explanation: In the above query we uses the findOne() method to retrieve a document from the users collection in MongoDB based on its unique _id value of ObjectId("6626039e9fe21c773b8bf207").

Example 2

// Finding a document by _id using findOne() 
db.users.findOne({ "_id": ObjectId("6626039e9fe21c773b8bf20b") });

Output:

{
_id: ObjectId('6626039e9fe21c773b8bf20b'),
name: 'Eve',
age: 28,
email: 'eve@example.com'
}

Explanation: In the above query we uses the findOne() method to retrieve a document from the users collection in MongoDB based on its unique _id value of ObjectId("6626039e9fe21c773b8bf20b").

Conclusion

Overall, Finding documents by their ID in MongoDB is a fundamental operation that allows us to retrieve specific records efficiently. By understanding the unique _id field, we can perform queries to fetch individual documents from collections. In this article, we explored how to find documents by ID in MongoDB using the findOne() method in the MongoDB shell and the findById() method in Mongoose. We covered concepts, examples, and outputs to help beginners understand and implement this essential MongoDB operation effectively.

Article Tags :