MongoDB query to find multiple matchings inside array of objects?

To find multiple matching conditions inside an array of objects in MongoDB, use $and operator combined with $elemMatch and $regex. The $and performs a logical AND operation on multiple expressions, while $elemMatch matches documents containing an array field with at least one element matching all criteria.

Syntax

db.collection.find({
    "$and": [
        { "arrayField": { "$elemMatch": { "field1": { $regex: /pattern/i } } } },
        { "arrayField": { "$elemMatch": { "field2": { $regex: /pattern/i } } } }
    ]
});

Sample Data

db.demo525.insertMany([
    { "details": [{ "Name": "Chris", "CountryName": "US" }] },
    { "details": [{ "Name": "Bob", "CountryName": "UK" }] },
    { "details": [{ "Name": "chris", "CountryName": "us" }] },
    { "details": [{ "Name": "Mike", "CountryName": "UK" }] }
]);

Display all documents from the collection ?

db.demo525.find();
{ "_id": ObjectId("5e8ae5ef437efc8605595b66"), "details": [{ "Name": "Chris", "CountryName": "US" }] }
{ "_id": ObjectId("5e8ae5f8437efc8605595b67"), "details": [{ "Name": "Bob", "CountryName": "UK" }] }
{ "_id": ObjectId("5e8ae602437efc8605595b68"), "details": [{ "Name": "chris", "CountryName": "us" }] }
{ "_id": ObjectId("5e8ae60b437efc8605595b69"), "details": [{ "Name": "Mike", "CountryName": "UK" }] }

Example: Find Multiple Matching Conditions

Find documents where Name starts with "Chris" (case-insensitive) AND CountryName starts with "us" (case-insensitive) ?

db.demo525.find({
    "$and": [
        { "details": { "$elemMatch": { "Name": { $regex: new RegExp('^' + 'Chris', 'i') } } } },
        { "details": { "$elemMatch": { "CountryName": { $regex: new RegExp('^' + 'us', 'i') } } } }
    ]
});
{ "_id": ObjectId("5e8ae5ef437efc8605595b66"), "details": [{ "Name": "Chris", "CountryName": "US" }] }
{ "_id": ObjectId("5e8ae602437efc8605595b68"), "details": [{ "Name": "chris", "CountryName": "us" }] }

Key Points

  • $and ensures ALL specified conditions must be satisfied
  • $elemMatch matches array elements containing objects with specific field conditions
  • $regex with 'i' flag provides case-insensitive pattern matching
  • The '^' anchor ensures the pattern matches from the beginning of the string

Conclusion

Combine $and, $elemMatch, and $regex to perform complex searches within arrays of objects. This approach allows case-insensitive pattern matching across multiple fields simultaneously.

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

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements