$in Operator - (MongoDB Misc)
The $in
operator in MongoDB is a query operator that selects documents where the value of a field equals any value in the specified array. In this page, we will discuss the syntax, example, output, explanation, use, important points, and summary of the $in
operator in MongoDB.
Syntax
The syntax for the $in
operator is as follows:
{
<field>: {
$in: [<value1>, <value2>, ... ]
}
}
Where:
<field>
: The name of the field to evaluate.$in
: The operator that selects the documents where the field has a value that matches any of the specified values.<value>
: The value or values to match against the field.
Example
Suppose you have a collection named employees
that consists of the following documents:
[
{
"name": "John Doe",
"department": "sales",
"age": 32,
"salary": 45000
},
{
"name": "Jane Smith",
"department": "marketing",
"age": 28,
"salary": 55000
},
{
"name": "Bob Johnson",
"department": "sales",
"age": 35,
"salary": 60000
},
{
"name": "Tom Brown",
"department": "engineering",
"age": 42,
"salary": 70000
}
]
The following example selects all documents where the department
field is either sales
or marketing
.
db.employees.find({ "department": { $in: ["sales", "marketing"] } })
Output
The above query will return the following output:
[
{
"name": "John Doe",
"department": "sales",
"age": 32,
"salary": 45000
},
{
"name": "Jane Smith",
"department": "marketing",
"age": 28,
"salary": 55000
},
{
"name": "Bob Johnson",
"department": "sales",
"age": 35,
"salary": 60000
}
]
Explanation
The $in
operator in MongoDB is used to select documents where the value of a field matches any of the specified values in an array. In the above example, the query selects all documents where the department
field has a value that matches either sales
or marketing
. This query is equivalent to the following SQL query:
SELECT * FROM employees WHERE department IN ('sales', 'marketing')
Use
The $in
operator in MongoDB is useful when you need to select documents where a field value matches any of the specified values. It saves the time of writing multiple OR conditions in a query.
Important Points
- The
$in
operator in MongoDB selects documents where the value of a field matches any of the specified values in an array. - You can use the
$in
operator with any valid data type. - The
$in
operator is case-sensitive.
Summary
In this page, we discussed the $in
operator in MongoDB. We covered the syntax, example, output, explanation, use, and important points of the $in
operator. By using the $in
operator in your queries, you can easily select documents where a field value matches any of the specified values in an array.