我想用SQL查询一些东西,比如查询:

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

如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。


当前回答

正则表达式的处理成本很高。

另一种方法是创建文本索引,然后使用$search进行搜索。

创建要搜索的字段的文本索引:

db.collection.createIndex({name: 'text', otherField: 'text'});

在文本索引中搜索字符串:

db.collection.find({
  '$text'=>{'$search': "The string"}
})

其他回答

如果您想在MongoDB中进行“like”搜索,那么应该使用$regex。通过使用它,查询将是:

db.product.find({name:{$regex:/m/i}})

有关更多信息,您也可以阅读文档-$regex

MongoRegex已被弃用。

使用MongoDB \ BSON \ Regex:

$regex = new MongoDB\BSON\Regex ( '^m');
$cursor = $collection->find(array('users' => $regex));
//iterate through the cursor

对于PHP mongo Like。

我对PHP mongo有几个问题。我发现串联正则表达式参数在某些情况下会有所帮助——PHP mongo find字段以开头。

例如

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)

我找到了一个免费的工具来将MySQL查询转换为MongoDB:http://www.querymongo.com/

我检查了几个问题。在我看来,几乎所有这些都是正确的。据此,答案是

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

如果您使用的是PHP,可以使用MongoDB数据对象包装器,如下所示:

$model = new MongoDB_DataObject();

$model->query("select * from users where name like '%m%'");

while($model->fetch()) {
    var_dump($model);
}

Or:

$model = new MongoDB_DataObject('users);

$model->whereAdd("name like '%m%'");

$model->find();

while($model->fetch()) {
    var_dump($model);
}