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
Search for multiple documents in MongoDB?
To search for multiple documents in MongoDB, use the $in operator to match documents where a field value equals any value in a specified array. This allows you to retrieve multiple documents with a single query instead of running separate queries for each value.
Syntax
db.collection.find({
"fieldName": { $in: [value1, value2, value3, ...] }
});
Sample Data
Let us create a collection with sample client documents ?
db.demo161.insertMany([
{"ClientId": 101, "ClientName": "Chris"},
{"ClientId": 102, "ClientName": "David"},
{"ClientId": 103, "ClientName": "David", "ClientAge": 35},
{"ClientId": 104, "ClientName": "Carol", "ClientAge": 31}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e3577cafdf09dd6d0853a09"),
ObjectId("5e3577d0fdf09dd6d0853a0a"),
ObjectId("5e3577dffdf09dd6d0853a0b"),
ObjectId("5e3577eefdf09dd6d0853a0c")
]
}
Display all documents from the collection ?
db.demo161.find();
{ "_id": ObjectId("5e3577cafdf09dd6d0853a09"), "ClientId": 101, "ClientName": "Chris" }
{ "_id": ObjectId("5e3577d0fdf09dd6d0853a0a"), "ClientId": 102, "ClientName": "David" }
{ "_id": ObjectId("5e3577dffdf09dd6d0853a0b"), "ClientId": 103, "ClientName": "David", "ClientAge": 35 }
{ "_id": ObjectId("5e3577eefdf09dd6d0853a0c"), "ClientId": 104, "ClientName": "Carol", "ClientAge": 31 }
Example: Search Multiple Documents Using $in
Find documents where ClientId matches any of the values 101, 103, or 104 ?
db.demo161.find({
"ClientId": { $in: [101, 103, 104] }
});
{ "_id": ObjectId("5e3577cafdf09dd6d0853a09"), "ClientId": 101, "ClientName": "Chris" }
{ "_id": ObjectId("5e3577dffdf09dd6d0853a0b"), "ClientId": 103, "ClientName": "David", "ClientAge": 35 }
{ "_id": ObjectId("5e3577eefdf09dd6d0853a0c"), "ClientId": 104, "ClientName": "Carol", "ClientAge": 31 }
Key Points
- The
$inoperator matches documents where the field value equals any value in the specified array. - Works with various data types: numbers, strings, ObjectIds, and dates.
- More efficient than multiple separate queries or using
$orwith equality conditions.
Conclusion
The $in operator provides an efficient way to search for multiple documents by matching field values against an array of possible values. It's ideal for retrieving specific records when you know the exact values you're looking for.
Advertisements
