Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to find through list of ids in MongoDB?
You can use the $in operator to find documents through a list of specific ids in MongoDB. The $in operator allows you to query multiple values in a single field, making it perfect for searching by multiple ObjectIds.
Syntax
db.collection.find({
_id: { $in: [ObjectId("id1"), ObjectId("id2"), ObjectId("id3")] }
});
Sample Data
Let's create a collection with sample student documents ?
db.findListOfIdsDemo.insertMany([
{"StudentName": "Carol", "StudentAge": 21},
{"StudentName": "Bob", "StudentAge": 25},
{"StudentName": "David", "StudentAge": 22},
{"StudentName": "John", "StudentAge": 20},
{"StudentName": "Mike", "StudentAge": 23}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c8ecadd2f684a30fbdfd575"),
ObjectId("5c8ecae42f684a30fbdfd576"),
ObjectId("5c8ecaed2f684a30fbdfd577"),
ObjectId("5c8ecaf82f684a30fbdfd578"),
ObjectId("5c8ecb092f684a30fbdfd579")
]
}
Display all documents from the collection ?
db.findListOfIdsDemo.find().pretty();
{
"_id": ObjectId("5c8ecadd2f684a30fbdfd575"),
"StudentName": "Carol",
"StudentAge": 21
}
{
"_id": ObjectId("5c8ecae42f684a30fbdfd576"),
"StudentName": "Bob",
"StudentAge": 25
}
{
"_id": ObjectId("5c8ecaed2f684a30fbdfd577"),
"StudentName": "David",
"StudentAge": 22
}
{
"_id": ObjectId("5c8ecaf82f684a30fbdfd578"),
"StudentName": "John",
"StudentAge": 20
}
{
"_id": ObjectId("5c8ecb092f684a30fbdfd579"),
"StudentName": "Mike",
"StudentAge": 23
}
Example: Find Documents by List of IDs
To find specific documents by their ObjectIds, create an array of ID strings and convert them to ObjectIds ?
var listOfIds = ['5c8ecae42f684a30fbdfd576', '5c8ecaf82f684a30fbdfd578'];
var documentIds = listOfIds.map(function(myId) { return ObjectId(myId); });
db.findListOfIdsDemo.find({_id: {$in: documentIds }}).pretty();
{
"_id": ObjectId("5c8ecae42f684a30fbdfd576"),
"StudentName": "Bob",
"StudentAge": 25
}
{
"_id": ObjectId("5c8ecaf82f684a30fbdfd578"),
"StudentName": "John",
"StudentAge": 20
}
Key Points
- The
$inoperator matches any value in the specified array - Convert string IDs to
ObjectId()format before using in queries - Use
map()function to efficiently convert arrays of string IDs
Conclusion
The $in operator with ObjectId conversion provides an efficient way to query multiple documents by their specific IDs in MongoDB. This approach is ideal for retrieving multiple records in a single query operation.
Advertisements
