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

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

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


当前回答

如果您使用的是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);
}

其他回答

使用聚合子字符串搜索(带索引!!!):

db.collection.aggregate([{
        $project : {
            fieldExists : {
                $indexOfBytes : ['$field', 'string']
            }
        }
    }, {
        $match : {
            fieldExists : {
                $gt : -1
            }
        }
    }, {
        $limit : 5
    }
]);

您可以使用where语句构建任何JavaScript脚本:

db.myCollection.find( { $where: "this.name.toLowerCase().indexOf('m') >= 0" } );

参考:$where

在PHP中,可以使用以下代码:

$collection->find(array('name'=> array('$regex' => 'm'));

可以使用正则表达式进行查询:

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

如果字符串来自用户,则可能需要在使用该字符串之前对其进行转义。这将防止来自用户的文字字符被解释为正则表达式标记。

例如,如果不转义,搜索字符串“A”也将匹配“AB”。在使用字符串之前,可以使用一个简单的替换来转义字符串

function textLike(str) {
  var escaped = str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
  return new RegExp(escaped, 'i');
}

所以现在,字符串变成了一个不区分大小写的模式,同时匹配文字点。例子:

>  textLike('A.');
<  /A\./i

现在,我们可以随时生成正则表达式了:

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

您可以在MongoDB中使用正则表达式。

例如

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