Using javascript RegExp
- split
name
string by space and make array of words - map to iterate loop and convert string to regex of each word of name
let name = "My Name".split("").map(n => new RegExp(n));console.log(name);
Result:
[/My/, /Name/]
There is 2 scenario to match string,
$in
:(it is similar to$or
condition)
Try $in Expressions, To include a regular expression in an $in
query expression, you can only use JavaScript regular expression objects (i.e. /pattern/ ). For example:
db.users.find({ name: { $in: name } }); // name = [/My/, /Name/]
$all
:(it is similar to$and
condition) a document should contain all words
db.users.find({ name: { $all: name } }); // name = [/My/, /Name/]
Using nested $and
and $or
conditional and $regex
There is 2 scenario to match string,
$or
:(it is similar to$in
condition)
db.users.find({ $or: [ { name: { $regex: "My" } }, { name: { $regex: "Name" } } // if you have multiple fields for search then repeat same block ]})
$and
:(it is similar to$all
condition) a document should contain all words
db.users.find({ $and: [ { $and: [ { name: { $regex: "My" } }, { name: { $regex: "Name" } } ] } // if you have multiple fields for search then repeat same block ]})