Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
-
$indexOfBytesreturns the index position where the substring is found, or -1 if not found -
$mapiterates through each element in the words array -
$anyElementTruereturns 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.
Advertisements
