MongoDB query to find matching documents given an array with values?

To find matching documents given an array with values in MongoDB, use the $in operator. This operator matches documents where the array field contains any of the specified values.

Syntax

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

Create Sample Data

Let us create a collection with documents containing project arrays ?

db.demo511.insertMany([
    {
        "ListOfProject": ["Library Management System", "Hospital Management System"]
    },
    {
        "ListOfProject": ["Online Web Tracking", "Library Management System"]
    },
    {
        "ListOfProject": ["Online Shopping Cart", "Hospital Management System"]
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e88473a987b6e0e9d18f585"),
        ObjectId("5e884751987b6e0e9d18f586"),
        ObjectId("5e884776987b6e0e9d18f587")
    ]
}

Display All Documents

View all documents in the collection ?

db.demo511.find();
{ "_id": ObjectId("5e88473a987b6e0e9d18f585"), "ListOfProject": [ "Library Management System", "Hospital Management System" ] }
{ "_id": ObjectId("5e884751987b6e0e9d18f586"), "ListOfProject": [ "Online Web Tracking", "Library Management System" ] }
{ "_id": ObjectId("5e884776987b6e0e9d18f587"), "ListOfProject": [ "Online Shopping Cart", "Hospital Management System" ] }

Example: Find Matching Documents

Find documents containing either "Hospital Management System" or "Online Shopping Cart" ?

db.demo511.find({
    "ListOfProject": { $in: ["Hospital Management System", "Online Shopping Cart"] }
});
{ "_id": ObjectId("5e88473a987b6e0e9d18f585"), "ListOfProject": [ "Library Management System", "Hospital Management System" ] }
{ "_id": ObjectId("5e884776987b6e0e9d18f587"), "ListOfProject": [ "Online Shopping Cart", "Hospital Management System" ] }

Key Points

  • The $in operator matches documents where the array contains any of the specified values
  • It performs an OR-like operation on array elements
  • Works with both array fields and single-value fields

Conclusion

Use the $in operator to efficiently find documents containing any of the specified array values. This provides a flexible way to match multiple criteria in a single query.

Updated on: 2026-03-15T03:21:01+05:30

246 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements