How to make “LIKE” query work in MongoDB?

后端 未结 7 1694
梦谈多话
梦谈多话 2021-01-03 00:07

I have a list of street names and I want to select all that start with \"Al\". In my MySQL I would do something like

SELECT * FROM streets WHERE \"street_nam         


        
相关标签:
7条回答
  • 2021-01-03 00:43

    Use a regular expression:

    db.streets.find( { street_name : /^Al/i } );
    

    or:

    db.streets.find( { street_name : { $regex : '^Al', $options: 'i' } } );
    

    http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-RegularExpressions

    Turning this into PHP:

    $regex = new MongoRegex("/^Al/i");
    $collection->find(array('street_name' => $regex));
    
    0 讨论(0)
  • 2021-01-03 00:43

    See: http://www.mongodb.org/display/DOCS/SQL+to+Mongo+Mapping+Chart

    Also, highly recommend just using the native mongodb connector from PHP instead of a wrapper. It's way faster than any wrapper.

    http://php.net/class.mongodb

    0 讨论(0)
  • 2021-01-03 00:43

    You can also do something like this

    ['key' => ['$regex' => '(?i)value']]
    
    0 讨论(0)
  • 2021-01-03 00:47

    here is my working example:

    <?php
    use MongoDB\BSON\Regex;
    $collection = $yourMongoClient->yourDatabase->yourCollection;
    $regex = new Regex($text, 's');
    $where = ['your_field_for_search' => $regex];
    $cursor = $collection->find($where);
    //Lets iterate through collection
    
    0 讨论(0)
  • 2021-01-03 00:47

    $collection.find({"name": /.*Al.*/})

    or, similar,

    $collection.find({"name": /Al/})

    You're looking for something that contains "Al" somewhere (SQL's '%' operator is equivalent to regexps' '.*'), not something that has "Al" anchored to the beginning of the string.

    0 讨论(0)
  • 2021-01-03 00:59

    MongoRegex has been deprecated.
    Use MongoDB\BSON\Regex

    $regex = new MongoDB\BSON\Regex ( '^A1');
    $cursor = $collection->find(array('street_name' => $regex));
    //iterate through the cursor
    
    0 讨论(0)
提交回复
热议问题