$in MongoDB Example

In this MongoDB tutorial, we will discuss the $in operator MongoDB. Additionally, we will also discuss the various examples where we will use the $in operator in MongoDB.

$in MongoDB

The $in operator in MongoDB is used to select the documents where the value of a field is equal to any value in the specified array.

Syntax:

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

Here, if the field contains an array, then the $in operator selects the documents whose field contains an array that contains at least one element that matches a value in the specified array.

Examples:

We will perform the following operations with examples:

  • Use the $in operator to match values
  • Use the $in operator to match values in an array
  • Use the $in operator with a regular expression
  • Use the $in aggregation operator specified value is in an array

Read MongoDB to find the last inserted document

1. Use the $in operator to match values

In this example, we will find the documents that match values using the $in operator in MongoDB.

We will insert the following documents into the inventory collection.

db.inventory.insertMany([
{ _id: 1, item: { name: "journal", code: "123" }, qty: 15, tags: [ "A", "B", "C" ], "city": "United States" },
{ _id: 2, item: { name: "notebook", code: "123" }, qty: 20, tags: [ "B" ], "city": "Canada" },
{ _id: 3, item: { name: "paper", code: "456" }, qty: 25, tags: [ "A", "B" ], "city": "USA" },
{ _id: 4, item: { name: "planner", code: "456" }, qty: 30, tags: [ "B", "A" ], "city": "Australia" },
{ _id: 5, item: { name: "postcard", code: "000" }, qty: 20, tags: [ [ "A", "B" ], "C" ], "city": "New Zealand" }
])

After that, we will apply the below query to find the documents that match values.

db.inventory.find( { qty: { $in: [ 5, 15 ] } } )

Here, this query will select all documents from the inventory collection where the qty value is either 5 or 15.

Use the $in Operator to Match Values
Use the $in Operator to Match Values

We have successfully retrieved the document where the qty value is either 5 or 15.

Note:

Although you can manifest this query using the $or operator, choose the $in operator rather than the $or operator when performing equality checks on the same field.

Read How to change collection name in MongoDB

2. Use the $in operator to match values in an array

In this example, we will use the same as we have used the previous example where documents that include the field tags, as in the following:

{ _id: 1, item: { name: "journal", code: "123" }, qty: 15, tags: [ "A", "B", "C" ] }

Then, the subsequent update() operation will set the sale field value to true where the tags field contains an array with at least one element matching either “A” or “B”.

db.inventory.update(
     { tags: { $in: ["A", "B"] } },
     { $set: { sale:true } }
)

Output:

Use the $in Operator to Match Values in an Array
Use the $in Operator to Match Values in an Array

We have successfully added the sale field using update operation where the tags field contains an array with at least one element matching either “A” or “B”.

Note:

By default, the update() method updates a single document. Include the option {multi: true} to update all documents that match the query criteria.

Read MongoDB remove an element from the array

3. Use the $in operator with a regular expression

The $in operator can specify matching values using regular expressions of the form /pattern/. You cannot use $regex operator expressions inside an $in.

We will insert the following documents into the details collection.

db.details.insertMany([
{_id: 1, item: "journal", qty: 15, tags: [ "appliances", "school", "clothing" ] },
{_id: 2, item: "notebook", qty: 20, tags: [ "school" ] },
{_id: 3, item: "paper", qty: 25, tags: [ "appliances", "school" ] },
{_id: 4, item: "planner", qty: 30, tags: [ "school", "appliances" ] },
{_id: 5, item: "postcard", qty: 20, tags: [ [ "appliances", "school" ], "clothing" ] }
])

After that, we will apply the below query for matching values using regular expressions of the form /pattern/.

db.details.find( { tags: { $in: [ /^cl/, /^be/ ] } } )

Here, this query selects all documents from the details collection where the tags field contains either a string that starts with cl or is or an array with at least one element that starts with cl or be.

Use the $in Operator with a Regular Expression
Use the $in Operator with a Regular Expression

We have successfully retrieved all the documents where the field contains either a string that starts with cl or be or an array with at least one element that starts with cl or be in MongoDB.

Check MongoDB compare two fields

4. Use the $in aggregation operator specified value is in an array

The $in (aggregation) will return a boolean indicating whether a specified value is in an array.

In MongoDB, the aggregation operation is used to process the data to return the computed result. We can perform various types of operations on that grouped data like sum, average, minimum, maximum, etc to return a computed result.

We will insert the following documents into the fruit collection.

db.fruit.insertMany([
{"_id": 1, "location": "24th Street, USA",
 "in_stock": [ "apples", "oranges", "bananas" ] },
{"_id": 2, "location": "36th Street, United States",
 "in_stock": [ "bananas", "pears", "grapes" ] },
{"_id": 3, "location": "82nd Street, Canada",
 "in_stock": [ "cantaloupes", "watermelons", "apples" ] }
])

After that, we will apply the following aggregation operation to check the in_stock array in each document and discover whether the string ‘bananas’ is there.

db.fruit.aggregate([
  {
    $project: {
      "store location" : "$location",
      "has bananas" : {
        $in: [ "bananas", "$in_stock" ]
      }
    }
  }
])

Output:

Use the $in aggregation operator specified value is in an array
Use the $in aggregation operator specified value is in an array

We have successfully returned a boolean indicating whether a specified value (banana) is in an array.

You may like the following MongoDB tutorials:

So, In this tutorial, we have understood the $in operator of MongoDB and we have also covered all the examples using $in operator in MongoDB with different variations.