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

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

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


当前回答

对于MongoDB Compass,您需要使用严格的模式语法,例如:

{ "text": { "$regex": "^Foo.*", "$options": "i" } }

(在MongoDB Compass中,使用“而不是”很重要)

其他回答

在Node.js项目中,使用Mongoose,使用类似的查询:

var User = mongoose.model('User');

var searchQuery = {};
searchQuery.email = req.query.email;
searchQuery.name = {$regex: req.query.name, $options: 'i'};
User.find(searchQuery, function(error, user) {
                if(error || user === null) {
                    return res.status(500).send(error);
                }
                return res.status(200).send(user);
            });

MongoRegex已被弃用。

使用MongoDB \ BSON \ Regex:

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

如果使用Node.js,它表示您可以编写以下内容:

db.collection.find( { field: /acme.*corp/i } );

// Or
db.collection.find( { field: { $regex: 'acme.*corp', $options: 'i' } } );

此外,您还可以这样写:

db.collection.find( { field: new RegExp('acme.*corp', 'i') } );

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

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

参考:$where

如果您使用的是Spring Data MongoDB,可以通过以下方式实现:

String tagName = "m";
Query query = new Query();
query.limit(10);
query.addCriteria(Criteria.where("tagName").regex(tagName));