Visit complete MongoDB roadmap

← Back to Topics List

$in

The $in operator in MongoDB is used to match any one of the values specified in an array. It can be used with a field that contains an array or with a field that holds a scalar value. This operator is handy when you want to filter documents based on multiple possible values for a specific field.

Syntax

Here’s the general structure of a query using the $in operator:

{ field: { $in: [<value1>, <value2>, ...] } }

Example

Consider a collection articles with the following documents:

[
  { _id: 1, title: 'MongoDB', tags: ['database', 'NoSQL'] },
  { _id: 2, title: 'Node.js', tags: ['javascript', 'runtime'] },
  { _id: 3, title: 'React', tags: ['library', 'javascript'] },
];

Let’s say you want to find all articles that have either the “NoSQL” or “javascript” tag. You can use the $in operator like so:

db.articles.find({ tags: { $in: ['NoSQL', 'javascript'] } });

This will return the following documents:

[
  { _id: 1, title: 'MongoDB', tags: ['database', 'NoSQL'] },
  { _id: 2, title: 'Node.js', tags: ['javascript', 'runtime'] },
  { _id: 3, title: 'React', tags: ['library', 'javascript'] },
];

In conclusion, the $in operator allows you to specify an array of values and filter documents based on whether their field value exists within that array.

Community

roadmap.sh is the 6th most starred project on GitHub and is visited by hundreds of thousands of developers every month.

Roadmaps Best Practices Guides Videos Store YouTube

roadmap.sh by Kamran Ahmed

Community created roadmaps, articles, resources and journeys to help you choose your path and grow in your career.

© roadmap.sh · FAQs · Terms · Privacy

ThewNewStack

The leading DevOps resource for Kubernetes, cloud-native computing, and the latest in at-scale development, deployment, and management.