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

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

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


当前回答

您有两个选择:

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

or

db.users.find({"name": {"$regex": "string", "$options": "i"}})

对于第二个,您有更多的选项,如选项中的“i”,以使用不区分大小写的方式查找。

关于“字符串”,可以使用“.string.”(%string%),或“string.*”(string%)和“.*string”(%sstring)。您可以根据需要使用正则表达式。

其他回答

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.* /})

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

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

In

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

您可以执行以下操作:

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

将模板文字与变量一起使用也有效:

{“firstname”:{$regex:`^${req.body.firstname}.*`,$options:'si'}}