MongoDB $in Query Operator

In MongoDB, the $in query operator selects the documents where the value of a field equals any value in the specified array.

The $in query operator is not to be confused with the $in aggregation pipeline operator, which returns a boolean indicating whether a specified value is in the array.

Example

Suppose we have a collection called products with the following documents:

{ "_id" : 1, "prod" : "Shorts" }
{ "_id" : 2, "prod" : "Jeans", "sizes" : null }
{ "_id" : 3, "prod" : "Shirt", "sizes" : "L" }
{ "_id" : 4, "prod" : "Shirt", "sizes" : "M" }
{ "_id" : 5, "prod" : "Bat", "sizes" : [ "S", "M", "XL", "XXL" ] }
{ "_id" : 6, "prod" : "Hat", "sizes" : [ "S", "L", "XL" ] }
{ "_id" : 7, "prod" : "Cap", "sizes" : [ "XS", "S", "M", "L", "XL" ] }

We can use the $in operator to select just those documents with specific _id values.

Example code:

db.products.find({ 
  _id: { $in: [ 1, 2, 3 ] } 
})

Result:

{ "_id" : 1, "prod" : "Shorts" }
{ "_id" : 2, "prod" : "Jeans", "sizes" : null }
{ "_id" : 3, "prod" : "Shirt", "sizes" : "L" }

In this case, we only wanted documents that contain an _id value of 1, 2, or 3.

Example 2

Here’s another example. This time we use $in against a different field.

db.products.find({ 
  sizes: { $in: [ "L" ] } 
})

Result:

{ "_id" : 3, "prod" : "Shirt", "sizes" : "L" }
{ "_id" : 6, "prod" : "Hat", "sizes" : [ "S", "L", "XL" ] }
{ "_id" : 7, "prod" : "Cap", "sizes" : [ "XS", "S", "M", "L", "XL" ] }

In this example we applied $in to the sizes field.

In this case, the first document had the value as a string, while the other two documents had it as an array element. Either way, all matching documents were returned.

Comparison of different types are evaluated according to the BSON comparison order.

Aggregation Example

We can use the same syntax when using the $match aggregation pipeline operator.

Example code:

db.products.aggregate(
   [
     { $match: { _id: { $in: [ 1, 2, 3 ] } } }
   ]
)

Result:

{ "_id" : 1, "prod" : "Shorts" }
{ "_id" : 2, "prod" : "Jeans", "sizes" : null }
{ "_id" : 3, "prod" : "Shirt", "sizes" : "L" }

And here it is again while querying the sizes field:

db.products.aggregate(
   [
     { $match: { sizes: { $in: [ "L" ] } } }
   ]
)

Result:

{ "_id" : 3, "prod" : "Shirt", "sizes" : "L" }
{ "_id" : 6, "prod" : "Hat", "sizes" : [ "S", "L", "XL" ] }
{ "_id" : 7, "prod" : "Cap", "sizes" : [ "XS", "S", "M", "L", "XL" ] }

Regular Expressions

You can use regular expressions in the query by using the form /pattern/.

Example:

db.products.find({ 
  sizes: { $in: [ /^X/ ] } 
})

Result:

{ "_id" : 5, "prod" : "Bat", "sizes" : [ "S", "M", "XL", "XXL" ] }
{ "_id" : 6, "prod" : "Hat", "sizes" : [ "S", "L", "XL" ] }
{ "_id" : 7, "prod" : "Cap", "sizes" : [ "XS", "S", "M", "L", "XL" ] }

In this example, I return all documents that have a sizes field with a value that is either a string that starts with X or an array where at least one of the elements starts with X.