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

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

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


当前回答

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

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

其他回答

MongoRegex已被弃用。

使用MongoDB \ BSON \ Regex:

$regex = new MongoDB\BSON\Regex ( '^m');
$cursor = $collection->find(array('users' => $regex));
//iterate through the cursor
>> db.car.distinct('name')
[ "honda", "tat", "tata", "tata3" ]

>> db.car.find({"name":/. *ta.* /})

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

例如

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

还可以按如下方式使用通配符过滤器:

{"query": { "wildcard": {"lookup_field":"search_string*"}}}

请务必使用*。

类似的查询如下所示:

db.movies.find({title: /.*Twelve Monkeys.*/}).sort({regularizedCorRelation : 1}).limit(10);

对于Scala ReactiveMongo API,

val query = BSONDocument("title" -> BSONRegex(".*" + name + ".*", "")) // like
val sortQ = BSONDocument("regularizedCorRelation" -> BSONInteger(1))
val cursor = collection.find(query).sort(sortQ).options(QueryOpts().batchSize(10)).cursor[BSONDocument]