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


For such evaluations, use aggregate() in MongoDB. Let us create a collection with documents −

> db.demo90.insertOne(
... {"words": ["john", "jace"]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2c1ada79799acab037af56")
}
> db.demo90.insertOne(
... {"words": ["sam", "adam"]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2c1adb79799acab037af57")
}

Display all documents from a collection with the help of find() method −

> db.demo90.find();

This will produce the following output −

{ "_id" : ObjectId("5e2c1ada79799acab037af56"), "words" : [ "john", "jace" ] }
{ "_id" : ObjectId("5e2c1adb79799acab037af57"), "words" : [ "sam", "adam" ] }

Following is the query to find documents whose array contains a string that is a substring of specific word −

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

This will produce the following output −

{ "_id" : ObjectId("5e2c1ada79799acab037af56"), "words" : [ "john", "jace" ] }

Updated on: 30-Mar-2020

641 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements