MongoDB query check if value in array property?

To check if a value exists in an array property in MongoDB, you can use the $in operator for exact matches. This operator searches for documents where the array field contains any of the specified values.

Syntax

db.collection.find({
    "arrayField": { $in: ["value1", "value2"] }
});

Sample Data

Let's create a collection with sample documents ?

db.valueInArrayDemo.insertMany([
    {
        "UserName": "John",
        "UserMessage": ["Hi", "Hello", "Bye"]
    },
    {
        "UserName": "Larry",
        "UserMessage": ["Thank You", "Amazing", "Nice"]
    },
    {
        "UserName": "Carol",
        "UserMessage": ["Awesome", "Bye", "Cool"]
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("..."),
        ObjectId("..."),
        ObjectId("...")
    ]
}

Display all documents from the collection ?

db.valueInArrayDemo.find().pretty();
{
    "_id": ObjectId("5cd684cf7924bb85b3f48959"),
    "UserName": "John",
    "UserMessage": [
        "Hi",
        "Hello",
        "Bye"
    ]
}
{
    "_id": ObjectId("5cd684d27924bb85b3f4895a"),
    "UserName": "Larry",
    "UserMessage": [
        "Thank You",
        "Amazing",
        "Nice"
    ]
}
{
    "_id": ObjectId("5cd684d87924bb85b3f4895b"),
    "UserName": "Carol",
    "UserMessage": [
        "Awesome",
        "Bye",
        "Cool"
    ]
}

Example: Check for Specific Value

Find all documents where the UserMessage array contains "Bye" ?

db.valueInArrayDemo.find({
    "UserMessage": { $in: ["Bye"] }
});
{ "_id": ObjectId("5cd684cf7924bb85b3f48959"), "UserName": "John", "UserMessage": ["Hi", "Hello", "Bye"] }
{ "_id": ObjectId("5cd684d87924bb85b3f4895b"), "UserName": "Carol", "UserMessage": ["Awesome", "Bye", "Cool"] }

Key Points

  • The $in operator returns documents where the array contains any of the specified values.
  • Use $in: ["value"] for single value checks or $in: ["val1", "val2"] for multiple values.
  • Alternative: Use direct equality {"arrayField": "value"} for single value matching.

Conclusion

The $in operator is the most efficient way to check if specific values exist in an array property. It performs exact matches and can search for multiple values simultaneously.

Updated on: 2026-03-15T01:15:02+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements