Open In App

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 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

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, Searching by ID in MongoDB is a fundamental operation for retrieving specific documents based on their unique identifiers. By understanding the “_id” field and ObjectIDs, we can efficiently query documents in MongoDB collections. In this article, we covered the process of searching by ID in MongoDB, explained the concept of ObjectIDs and provided examples with explanations and demonstrated sample outputs.

Article Tags :