Search code examples
regexmongodbaggregate

How to find middle of the string, next to space and dot in MongoDB


 [
    {
        "Name": "Dr.Soma",
        "Email": "drsoma@gmail.com",
        "MobNo": 111111111
    }, 
   {
        "Name": "Bootha Ganesh",
        "Email": "boothaganesg@gmail.com",
        "MobNo": 222222222
    }, 
   {
        "Name": "Steven",
        "Email": "steven@gmail.com",
        "MobNo": 333333333
    },
    {
            "Name": "Dr.Anbarasi",
            "Email": "anbarasi@gmail.com",
            "MobNo": 4444444444
     }
     ]

I try this to using find regex

db.details.find({Name:{$regex:/steven/i}})

output:

   {
      "Name": "Steven",
      "Email": "steven@gmail.com",
      "MobNo": 333333333
    }

How to find data Name dot(.) after Soma & Space after Ganesh
Excepted Output
If I find Name Ganesh,I need

{
            "Name": "Bootha Ganesh",
            "Email": "boothaganesg@gmail.com",
            "MobNo": 222222222
  }

If I find Name small s or capital S ,I need

{
        "Name": "Dr.Soma",
        "Email": "drsoma@gmail.com",
        "MobNo": 111111111
 }

No Need Name Dr.Anbarasi data


Solution

  • db.collection.find({"Name": {'$regex': /\bsoma[a-zA-Z0-9]*/gi}})
    

    \b assert position at a word boundary: (^\w | \w$ | \W\w|\w\W)
    soma-for searching value
    [a-zA-Z0-9]-word characters
    *-to entire string