skip to Main Content

I’m trying to make queries to my DB -mongo based- but I need them to be partial, lets say, I need the DB to find results when I’m entering something in an input box. For example, lets supose that in my DB there are a lot of users with different names "Paul, Patrick, Pablo, Pantaleon, etc", I need mongo to make a search a throw me the results when in the input I put "pa". I honestly don’t know the sintax to do it, because the model.Find({name:""}) just gets the results when you enter the full name….

I’d appreciate a lot if someone can help me with this doubt!
Thanks!!!

2

Answers


  1. I will recommend the operator $regex:

    what is $regex: Provides regular expression capabilities for pattern matching strings in queries. MongoDB uses Perl compatible regular expressions (i.e. "PCRE" ) version 8.42 with UTF-8 support.

    {name:{$regex: "/pa/",$options:'i'}}
    

    The $options with ‘I’ parameter (which means case insensitivity) specifies that we want to carry out the search no matter if we find the letters ‘Gu’ in lower or upper case.

    for know more of it https://www.mongodb.com/docs/manual/reference/operator/query/regex/

    Login or Signup to reply.
  2. As I am able to get your point.

    You can try this –

     db.userCollection.find( {name: {$regex: /^pa/}} )
    
     - will match 'Paul', 'Patrick', 'Pablo', 'Pantaleon', but not 'john', 'prince'.
    

    To understand in detail you can follow mongodb docs

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search