Open In App

How to Search by id in MongoDB

Last Updated : 31 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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").


Next Article
Article Tags :

Similar Reads