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 equivalent of WHERE IN(1,2,...)?
The MongoDB equivalent of SQL's WHERE IN(1,2,...) clause is the $in operator. This operator allows you to match documents where a field value equals any value in a specified array.
Syntax
db.collectionName.find({
fieldName: { $in: [value1, value2, value3, ...] }
});
Sample Data
Let us create a collection with student documents ?
db.whereInDemo.insertMany([
{ "StudentName": "John", "StudentMathScore": 57 },
{ "StudentName": "Larry", "StudentMathScore": 89 },
{ "StudentName": "Chris", "StudentMathScore": 98 },
{ "StudentName": "Robert", "StudentMathScore": 99 },
{ "StudentName": "Bob", "StudentMathScore": 97 }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5ca281ec6304881c5ce84ba5"),
ObjectId("5ca281f56304881c5ce84ba6"),
ObjectId("5ca281fd6304881c5ce84ba7"),
ObjectId("5ca2820a6304881c5ce84ba8"),
ObjectId("5ca282206304881c5ce84ba9")
]
}
Example: Using $in Operator
Find students with math scores of 97, 98, or 99 ?
db.whereInDemo.find({
StudentMathScore: { $in: [97, 98, 99] }
});
{
"_id": ObjectId("5ca281fd6304881c5ce84ba7"),
"StudentName": "Chris",
"StudentMathScore": 98
}
{
"_id": ObjectId("5ca2820a6304881c5ce84ba8"),
"StudentName": "Robert",
"StudentMathScore": 99
}
{
"_id": ObjectId("5ca282206304881c5ce84ba9"),
"StudentName": "Bob",
"StudentMathScore": 97
}
Key Points
- The
$inoperator matches documents where the field value equals any value in the array. - It works with numbers, strings, dates, and other data types.
- Use
$ninfor the opposite operation (NOT IN).
Conclusion
MongoDB's $in operator provides the same functionality as SQL's WHERE IN clause. It efficiently matches documents where a field contains any value from a specified array of options.
Advertisements
