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

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

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


当前回答

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

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

其他回答

In

使用Python的PyMongoMongoose使用Node.jsJongo,使用Javamgo,使用Go

您可以执行以下操作:

db.users.find({'name': {'$regex': 'sometext'}})

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

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

您可以使用MongoDB 2.6的新功能:

db.foo.insert({desc: "This is a string with text"});
db.foo.insert({desc:"This is a another string with Text"});
db.foo.ensureIndex({"desc":"text"});
db.foo.find({
    $text:{
        $search:"text"
    }
});

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

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

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

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