0
0
MongoDBquery~5 mins

$in for matching a set in MongoDB

Choose your learning style9 modes available
Introduction

The $in operator helps you find documents where a field's value matches any value from a list you provide. It makes searching for multiple possible values easy.

You want to find all users whose favorite color is either red, blue, or green.
You need to get all orders with statuses like 'shipped', 'delivered', or 'processing'.
You want to find products that belong to any of several categories.
You want to filter records where a field matches any value from a small set of options.
Syntax
MongoDB
{ field: { $in: [value1, value2, ...] } }

The $in operator takes an array of values to match against.

It returns documents where the field's value is equal to any value in the array.

Examples
Finds documents where the color field is either "red" or "blue".
MongoDB
{ color: { $in: ["red", "blue"] } }
Finds documents where the status field matches any of the three listed statuses.
MongoDB
{ status: { $in: ["shipped", "delivered", "processing"] } }
Finds documents where the age field is 25, 30, or 35.
MongoDB
{ age: { $in: [25, 30, 35] } }
Sample Program

This query finds all users whose favoriteFruit is either "apple" or "banana".

MongoDB
db.users.find({ favoriteFruit: { $in: ["apple", "banana"] } })
OutputSuccess
Important Notes

If the field does not exist in a document, that document will not match.

You can use $in with any data type: strings, numbers, ObjectIds, etc.

Summary

$in helps find documents matching any value from a list.

Use it when you want to check a field against multiple possible values.

The syntax is simple: provide an array of values inside $in.