How to Find Documents by ID in MongoDB?
Last Updated :
24 Apr, 2024
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
- MongoDB uses IDs to uniquely identify each document in a collection.
- The
_id
field serves as the primary key for documents.
- MongoDB IDs are 12-byte identifiers.
- They consist of a timestamp, a machine identifier, a process ID, and a counter.
Types of _id Values
- The most common type of MongoDB ID is
ObjectId
.
ObjectId
is a 12-byte value consisting of:
- A 4-byte timestamp representing the ObjectId's creation, measured in seconds since the Unix epoch.
- A 5-byte random value.
- A 3-byte incrementing counter and initialized to a random value.
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: '[email protected]'
},
{
_id: ObjectId('6626039e9fe21c773b8bf208'),
name: 'Bob',
age: 25,
email: '[email protected]'
},
{
_id: ObjectId('6626039e9fe21c773b8bf209'),
name: 'Charlie',
age: 35,
email: '[email protected]'
},
{
_id: ObjectId('6626039e9fe21c773b8bf20a'),
name: 'David',
age: 40,
email: '[email protected]'
},
{
_id: ObjectId('6626039e9fe21c773b8bf20b'),
name: 'Eve',
age: 28,
email: '[email protected]'
}
]
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: '[email protected]'
}
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: '[email protected]'
}
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.
Similar Reads
How to Find Duplicates in MongoDB
Duplicates in a MongoDB collection can lead to data inconsistency and slow query performance. Therefore, it's essential to identify and handle duplicates effectively to maintain data integrity. In this article, we'll explore various methods of how to find duplicates in MongoDB collections and discus
4 min read
How to Search by id in MongoDB
In MongoDB, each document in a collection is uniquely identified by a field called "_id". This "_id" field serves as the primary key and provides a unique identifier for each document. Searching by ID is a common operation in MongoDB and allows us to retrieve specific documents based on their unique
4 min read
How to Update the _id of MongoDB Document?
In MongoDB, the _id field serves as a unique identifier for each document in a collection. While MongoDB automatically generates _id values for documents upon insertion, there are scenarios where we might need to update the _id of a document. In this article, We will learn about How to update the _i
3 min read
MongoDB CRUD Operations: Insert and Find Documents
MongoDB is a NoSQL database that allows for flexible and scalable data storage using a document-based model. CRUD (Create, Read, Update, Delete) operations form the backbone of any database interaction and in MongoDB, these operations are performed on documents within collections. In this article, w
3 min read
Sorting Documents in MongoDB
Sorting documents in MongoDB is the process of arranging data in a specific order based on field values, enhancing the efficiency and readability of query results. In this article, We will learn about Sorting Documents in MongoDB by understanding various examples in detail.Sorting Documents in Mongo
4 min read
How To Query For Documents In MongoDB Using NodeJS?
MongoDB is the popular NoSQL database that allows for flexible and scalable data storage. NodeJS and JavaScript runtime built on Chrome's V8 JavaScript engine. It is often used with MongoDB to build powerful and efficient applications. In this article, we will guide you on how to query the documents
4 min read
Modify Valid or Invalid Documents in MongoDB
In MongoDB, maintaining data consistency and integrity is crucial especially when working with collections that have specific validation rules. A document is considered valid if it follows to the predefined schema or validation rules of a collection otherwise, it is invalid. In this article, we will
4 min read
Filtering MongoDB Documents by ID in Node.js with Express.js
Filtering is a very basic feature that an API must possess to serve data to the client application efficiently. By handling these operations on the server side, we can reduce the amount of processing that has to be done on the client application, thereby increasing its performance. In this article,
4 min read
How is id Generated in MongoDB
In MongoDB, each document stored in a collection is uniquely identified by a field called _id. This _id field serves as the primary key for the document and is important for ensuring document uniqueness and efficient retrieval. But have you ever wondered how these _id values are generated in MongoDB
3 min read
How to find all the document keys of MongoDB using Node.js ?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This fo
1 min read