$in
The $in aggregation operator checks if a specified value exists within an array. It returns true if the value is found in the array, and false otherwise.
Parameters
-
value: The value to search for. -
array: The array to search within.
Example (MongoDB Shell)
The following example demonstrates using the $in operator to check if a specific skill exists in each employee's skill set.
Create sample documents
db.employees.insertMany([ { _id: 1, name: "Sarah", skills: ["Python", "JavaScript", "SQL"] }, { _id: 2, name: "Mike", skills: ["Java", "C++", "Go"] }, { _id: 3, name: "Emma", skills: ["Python", "Ruby", "Rust"] } ]);
Query example
db.employees.aggregate([ { $project: { name: 1, hasPython: { $in: ["Python", "$skills"] } } } ]);
Output
[
{ _id: 1, name: 'Sarah', hasPython: true },
{ _id: 2, name: 'Mike', hasPython: false },
{ _id: 3, name: 'Emma', hasPython: true }
]
Code examples
To view a code example for using the $in aggregation operator, choose the tab for the language that you want to use: