How to Search by id in MongoDB
Last Updated :
31 Jul, 2024
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 identifiers.
In this article, we'll explore how to search by ID in MongoDB by covering concepts and examples to understand the process effectively.
Understanding ObjectIDs in MongoDB
- In MongoDB, each document in a collection has a unique identifier called
_id
.
- This field is automatically generated by MongoDB and is of type
ObjectId
.
- The
_id
field ensures the uniqueness of each document within a collection and is indexed by default for fast retrieval.
- The
find
method in MongoDB is used to query documents in a collection.
- To search for a document by its
_id
, we can pass an object with the _id
value to the find
method.
Syntax:
db.collectionName.find({ _id: ObjectId("your_id_here") })
Replace collectionName
with the name of our collection and your_id_here
with the actual _id
value we want to search for. MongoDB will return the document with the matching _id
.
Examples of How to search by id in mongoDB
Let's set up an Environment:
To understand How to search 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("5f76e3d4b03f5d0012c279c7"), "name": "Alice", "age": 30 },
{ "_id": ObjectId("5f76e3e4b03f5d0012c279c8"), "name": "Bob", "age": 35 },
{ "_id": ObjectId("5f76e3f1b03f5d0012c279c9"), "name": "Charlie", "age": 40 },
{ "_id": ObjectId("5f76e3f9b03f5d0012c279ca"), "name": "David", "age": 45 },
{ "_id": ObjectId("5f76e404b03f5d0012c279cb"), "name": "Eve", "age": 50 },
{ "_id": ObjectId("5f76e40fb03f5d0012c279cc"), "name": "Frank", "age": 55 },
{ "_id": ObjectId("5f76e416b03f5d0012c279cd"), "name": "Grace", "age": 60 },
{ "_id": ObjectId("5f76e41eb03f5d0012c279ce"), "name": "Hannah", "age": 65 },
{ "_id": ObjectId("5f76e426b03f5d0012c279cf"), "name": "Ivy", "age": 70 },
{ "_id": ObjectId("5f76e42eb03f5d0012c279d0"), "name": "Jack", "age": 75 }
]
Example 1: Simple Search
Let's retrieves the document in the "users" collection that has an "_id" equal to ObjectId("5f76e3d4b03f5d0012c279c7")
.
db.users.find({ _id: ObjectId("5f76e3d4b03f5d0012c279c7") })
Output:
{ "_id": ObjectId("5f76e3d4b03f5d0012c279c7"), "name": "Alice", "age": 30 }
Example 2: Searching by _id with Node.js Driver
- Let's Write a Node.js function to connect to a MongoDB database and retrieve a document from the "users" collection using its ObjectID (
5f76e3e4b03f5d0012c279c8
).
- Log the search result to the console. Use
MongoClient
and ObjectId
from the mongodb
package and handle errors easily.
const { MongoClient, ObjectId } = require('mongodb');
async function searchById() {
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
const database = client.db('mydb');
const collection = database.collection('users');
const result = await collection.findOne({ _id: new ObjectId("5f76e3e4b03f5d0012c279c8") });
console.log('Search result:', result);
} finally {
await client.close();
}
}
searchById().catch(console.error);
Output:
Search result: { _id: 5f76e3e4b03f5d0012c279c8, name: 'Bob', age: 35 }
Example 3: Searching by _id Using Mongoose
- In a Node.js application using Mongoose, define a schema for a "User" collection with fields "name" (String) and "age" (Number). Create a model for the "User" collection.
- Use the
findById
method to search for a document in the "User" collection with the _id 5f76e3f1b03f5d0012c279c9
and log the result to the console. Handle any errors that may occur during the search operation.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Define a schema
const userSchema = new Schema({
name: String,
age: Number
});
// Create a model
const User = mongoose.model('User', userSchema);
// Search for a document by _id
User.findById('5f76e3f1b03f5d0012c279c9', (err, user) => {
if (err) {
console.error(err);
} else {
console.log(user);
}
});
Output:
{ "_id": "5f76e3f1b03f5d0012c279c9", "name": "Charlie", "age": 40 }
Conclusion
Overall, The _id
field in MongoDB is crucial for uniquely identifying documents within a collection. Whether using the MongoDB shell, native driver or Mongoose, querying documents by their _id
is a common and efficient operation. Understanding how to work with ObjectId
and the _id
field can greatly enhance your ability to manage and retrieve data in MongoDB.
What is an ObjectId in MongoDB?
An ObjectId
is a 12-byte identifier used as a unique identifier for documents in MongoDB. It includes a timestamp, machine identifier, process ID, and a counter, ensuring uniqueness.
Can I provide a custom _id
when inserting a document in MongoDB?
Yes, you can provide a custom value for the _id
field. If not specified, MongoDB automatically generates an ObjectId
.
How can I convert a string to an ObjectId in MongoDB?
In the MongoDB shell or a Node.js application, you can convert a string to an ObjectId
using the ObjectId()
constructor, e.g., ObjectId("your_id_here")
.
Similar Reads
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 I
3 min read
How to Get String Length in MongoDB
In MongoDB, determining the length of a string stored in a document can be useful for various data processing tasks and queries. MongoDB provides several operators and methods that allow us to calculate the length of strings efficiently. In this article, we will explore how to get the string length
5 min read
How MongoDB sort by relevance in Node.js ?
MongoDB is a popular, open-source NoSQL database that uses a document-oriented data model. It is designed to handle large amounts of data with high performance and scalability and is often used in big data and real-time web applications. In MongoDB, data is stored in BSON (binary JSON) format, which
4 min read
MongoDB Text Search
MongoDB Text Search is a powerful feature designed to find specified text within string content in MongoDB collections. This capability is essential for applications that require efficient and effective searching capabilities. Text indexes in MongoDB should be strings or arrays of string elements an
7 min read
How to Set a Primary Key in MongoDB?
In MongoDB, primary keys play an important role in uniquely identifying documents within a collection. While MongoDB doesn't have a concept of primary keys in the same way as relational databases but it allows for the creation of unique identifiers for documents. In this article, we'll explore how t
3 min read
How to Query MongoDB with "like"?
Querying data in MongoDB often requires pattern-matching operations similar to SQL's "LIKE" operator. While MongoDB doesn't have a direct "LIKE" operator, it offers the $regex operator and regular expressions for achieving similar functionality. In this article, We will learn about How to Query Mong
3 min read
How to Use $unwind Operator in MongoDB?
MongoDB $unwind operator is an essential tool for handling arrays within documents. It helps deconstruct arrays, converting each array element into a separate document, which simplifies querying, filtering, and aggregation in MongoDB.By understanding the MongoDB $unwind syntax users can utilize this
6 min read
How to use MongoDB Projection in Mongoose?
MongoDB projection in Mongoose allows you to specify which fields to include or exclude in query results, optimizing data retrieval by returning only the necessary information from the database.Prerequisites:Nodejs NPMMongoDBJavaScriptThere are several ways to specify projection in Mongoose:Table of
4 min read
How To Use the MongoDB Shell
The MongoDB Shell, also known as mongosh is a powerful command-line interface that allows users to interact with MongoDB databases. It provides a REPL (Read-Eval-Print Loop) environment that facilitates database management, data manipulation, and administrative tasks with easeIn this comprehensive g
7 min read
MongoDB $in Operator
MongoDB $in operator provides a powerful way to query documents based on multiple potential values for a specific field within a single query.In this article, We will learn about the MongoDB $in Operator by understanding various examples in detail.MongoDB $in OperatorThe MongoDB $in operator is used
4 min read