How to query MongoDB with “like” ?



  • 3 Answer(s)

    This could be a best answer, Try by using below code:

    db.users.find({"name": /.*m.*/})
    

    or, related:

    db.users.find({"name": /m/})
    

    We are expecting  for something that contains “m” somewhere (SQL’s ‘%‘ operator is equivalent to Regexp’s ‘.*‘), not something that has “m” anchored to the beginning of the string.

    Answered on December 21, 2018.
    Add Comment

    This is the alternative solution for the issue :

    db.users.insert({name: 'paulo'})
    db.users.insert({name: 'patric'})
    db.users.insert({name: 'pedro'})
     
    db.users.find({name: /a/}) //like '%a%'
    

    output: paulo, patric

    db.users.find({name: /^pa/}) //like 'pa%'
    

    output: paulo, patric

    db.users.find({name: /ro$/}) //like '%ro'
    

    output: pedro

    Answered on December 21, 2018.
    Add Comment

    The following code can be used in PHP:

    $collection->find(array('name'=> array('$regex' => 'm'));
    
    Answered on December 21, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.