How to query MongoDB with “like”?

后端 未结 30 2668
予麋鹿
予麋鹿 2020-11-21 05:51

I want to query something with SQL\'s like query:

SELECT * FROM users  WHERE name LIKE \'%m%\'

How to do I achieve the same in

30条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-21 06:12

    For PHP mongo Like.
    I had several issues with php mongo like. i found that concatenating the regex params helps in some situations PHP mongo find field starts with. I figured I would post on here to contribute to the more popular thread

    e.g

    db()->users->insert(['name' => 'john']);
    db()->users->insert(['name' => 'joe']);
    db()->users->insert(['name' => 'jason']);
    
    // starts with
    $like_var = 'jo';
    $prefix = '/^';
    $suffix = '/';
    $name = $prefix . $like_var . $suffix;
    db()->users->find(['name' => array('$regex'=>new MongoRegex($name))]);
    output: (joe, john)
    
    // contains
    $like_var = 'j';
    $prefix = '/';
    $suffix = '/';
    $name = $prefix . $like_var . $suffix;
    db()->users->find(['name' => array('$regex'=>new MongoRegex($name))]);
    
    output: (joe, john, jason)
    

提交回复
热议问题