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
Get the array of _id in MongoDB?
In MongoDB, the _id field is a mandatory field that acts as the primary key for each document. To retrieve documents by matching their _id values against an array of specific values, use the $in operator.
Syntax
db.collectionName.find({ _id: { $in: [value1, value2, value3, ...] } });
Create Sample Data
db.selectInWhereIdDemo.insertMany([
{"_id": 23},
{"_id": 28},
{"_id": 45},
{"_id": 75},
{"_id": 85},
{"_id": 145}
]);
{
"acknowledged": true,
"insertedIds": [23, 28, 45, 75, 85, 145]
}
Display All Documents
db.selectInWhereIdDemo.find();
{ "_id": 23 }
{ "_id": 28 }
{ "_id": 45 }
{ "_id": 75 }
{ "_id": 85 }
{ "_id": 145 }
Example: Get Documents with Specific _id Values
Retrieve documents where _id matches any value in the array [23, 45, 85, 145] ?
db.selectInWhereIdDemo.find({ _id: { $in: [23, 45, 85, 145] } });
{ "_id": 23 }
{ "_id": 45 }
{ "_id": 85 }
{ "_id": 145 }
Key Points
- The
$inoperator matches documents where the field value equals any value in the specified array. - Works with any data type for _id values (ObjectId, numbers, strings).
- Returns documents in the order they appear in the collection, not the array order.
Conclusion
Use the $in operator with an array of _id values to efficiently retrieve multiple documents by their primary keys. This method is ideal for batch document retrieval operations.
Advertisements
