How to Search in the Specified Array in MongoDB

Shihab Sikder Feb 02, 2024
How to Search in the Specified Array in MongoDB

The $in operator searches within the array you’ve provided. For example, if you give an array and want to search one or more matched elements in a MongoDB collection, then you can use $in.

Use the $in Operator to Search in the Specified Array in MongoDB

The $in operator finds documents where a field’s value equals any value in the provided array. Use the following prototype to specify an $in expression.

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

For example, let’s say you have the following collection.

{
    _id:1,
    name: "John",
    age: 30
},
{
    _id:2,
    name: "Alex",
    age: 23
},
{
    _id:3,
    name: "Murphy",
    age: 25
},
{
    _id:4,
    name: "Alice",
    age: 28
},

Now, you want to see the documents for _id = 2,3,4. So, the command will be like the following.

db.collection.find( {_id: { $in: [2, 3, 4] } } );

Or, you can also send an array as the parameter. When you’re developing apps or websites, then it will be useful.

let list=[2, 3, 4]
db.collection.find( { _id:{ $in: list} } )

While using JavaScript promises, this approach is useful.

To avoid error, you should be aware of the ObjectId. _id is by default provided by MongoDB, and the type of _id is ObjectId.

So, while passing the array in the parameter of $in, it’s better to convert each integer id to ObjectId like the following.

{ "_id" : { $in : [ObjectId('2'),ObjectId('3'),ObjectId('4')] } }

This approach is more accurate because you provide the exact data type of the _id through the parameter. $in can be used in updateMany, updateOne, deleteOne, deleteMany operations as well.

To know more about the $in operator, visit the official page here.

Shihab Sikder avatar Shihab Sikder avatar

I'm Shihab Sikder, a professional Backend Developer with experience in problem-solving and content writing. Building secure, scalable, and reliable backend architecture is my motive. I'm working with two companies as a part-time backend engineer.

LinkedIn Website