Quantcast
Channel: How to query MongoDB with "like" - Stack Overflow
Viewing all articles
Browse latest Browse all 48

Answer by turivishal for How to query MongoDB with "like"?

$
0
0

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,

  1. $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/]
  1. $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,

  1. $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  ]})

Playground

  1. $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  ]})

Playground


Viewing all articles
Browse latest Browse all 48

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>