MENU

芒果MongoDB 模糊搜索查询

March 25, 2019 • 已被 213 位童鞋围观过 • 代码分享

MongoDB查询条件可以使用正则表达式,从而实现模糊查询的功能。模糊查询可以使用$regex操作符或直接使用正则表达式对象。

MySQL

select * from student where name like ’%joe%’
select * from student where name regexp ’joe’

MongoDB

db.student.find({name:{$regex:/joe/}})
db.student.find({name:/joe/})

模糊查询:uname包含某个关键字测试'

{"uname": {$regex: '阳', $options:'i'}}

php 代码如下

$query = [
    'uname' => new Regex('老婆', 'i')
];
$options = [];
$cursor = $collection->find($query, $options);
foreach ($cursor as $document) {
    echo $document['_id'] . "\n";
}
Last Modified: September 28, 2023