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
MongoDB find by multiple array items using $in?
To find documents by multiple array items in MongoDB, use the $in operator. This operator matches documents where the array field contains any of the specified values.
Syntax
db.collection.find({
"arrayField": { $in: ["value1", "value2", "value3"] }
});
Sample Data
db.findByMultipleArrayDemo.insertMany([
{
"StudentFirstName": "John",
"StudentLastName": "Smith",
"StudentCoreSubject": ["Compiler", "Operating System", "Computer Networks"]
},
{
"StudentFirstName": "Carol",
"StudentLastName": "Taylor",
"StudentCoreSubject": ["MongoDB", "MySQL", "SQL Server"]
},
{
"StudentFirstName": "Bob",
"StudentLastName": "Taylor",
"StudentCoreSubject": ["MongoDB", "MySQL", "SQL Server"]
},
{
"StudentFirstName": "David",
"StudentLastName": "Johnson",
"StudentCoreSubject": ["Compiler", "Operating System", "Computer Networks"]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c7ef07b559dd2396bcfbfc4"),
ObjectId("5c7ef09d559dd2396bcfbfc5"),
ObjectId("5c7ef0c7559dd2396bcfbfc6"),
ObjectId("5c7ef0f2559dd2396bcfbfc7")
]
}
Example: Find Students with Specific Subjects
Find students who study either "Compiler" or "Computer Networks" ?
db.findByMultipleArrayDemo.find({
StudentCoreSubject: { $in: ["Compiler", "Computer Networks"] }
}).pretty();
{
"_id": ObjectId("5c7ef07b559dd2396bcfbfc4"),
"StudentFirstName": "John",
"StudentLastName": "Smith",
"StudentCoreSubject": [
"Compiler",
"Operating System",
"Computer Networks"
]
}
{
"_id": ObjectId("5c7ef0f2559dd2396bcfbfc7"),
"StudentFirstName": "David",
"StudentLastName": "Johnson",
"StudentCoreSubject": [
"Compiler",
"Operating System",
"Computer Networks"
]
}
Key Points
- The
$inoperator returns documents if the array contains at least one matching value. - Use
$alloperator if you need documents containing all specified values. - Works with both array fields and single value fields.
Conclusion
The $in operator efficiently finds documents where array fields contain any of the specified values. This is ideal for filtering documents based on multiple possible array elements.
Advertisements
