MongoDB query to find documents whose array contains a string that is a substring of a specific word

To find documents whose array contains a string that is a substring of a specific word, use MongoDB's aggregation pipeline with $match, $expr, and $anyElementTrue operators combined with $indexOfBytes to check substring matches.

Syntax

db.collection.aggregate([
    { 
        $match: { 
            $expr: { 
                $anyElementTrue: { 
                    $map: { 
                        input: "$arrayField", 
                        as: "element", 
                        in: { 
                            $ne: [ -1, { $indexOfBytes: [ "targetWord", "$$element" ] } ] 
                        } 
                    } 
                } 
            } 
        } 
    }
]);

Sample Data

db.demo90.insertMany([
    { "words": ["john", "jace"] },
    { "words": ["sam", "adam"] }
]);
{
    "acknowledged": true,
    "insertedIds": {
        "0": ObjectId("5e2c1ada79799acab037af56"),
        "1": ObjectId("5e2c1adb79799acab037af57")
    }
}

View Sample Data

db.demo90.find();
{ "_id": ObjectId("5e2c1ada79799acab037af56"), "words": ["john", "jace"] }
{ "_id": ObjectId("5e2c1adb79799acab037af57"), "words": ["sam", "adam"] }

Example: Find Documents with Substring Match

Find documents where any array element is a substring of the word "john" ?

db.demo90.aggregate([
    { 
        $match: { 
            $expr: { 
                $anyElementTrue: { 
                    $map: { 
                        input: "$words", 
                        as: "j", 
                        in: { 
                            $ne: [ -1, { $indexOfBytes: [ "john", "$$j" ] } ] 
                        } 
                    } 
                } 
            } 
        } 
    }
]);
{ "_id": ObjectId("5e2c1ada79799acab037af56"), "words": ["john", "jace"] }

How It Works

  • $indexOfBytes returns the index position where the substring is found, or -1 if not found
  • $map iterates through each element in the words array
  • $anyElementTrue returns true if any mapped element satisfies the condition
  • $ne: [-1, ...] checks that the substring was found (index is not -1)

Conclusion

Use MongoDB's aggregation pipeline with $indexOfBytes and $anyElementTrue to find documents where array elements are substrings of a target word. This method efficiently searches for partial string matches within array fields.

Updated on: 2026-03-15T01:53:18+05:30

821 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements