我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
当前回答
如果您有字符串变量,则必须将其转换为正则表达式,因此MongoDB将对其使用类似的语句。
const name = req.query.title; //John
db.users.find({ "name": new Regex(name) });
结果与:
db.users.find({"name": /John/})
其他回答
类似的查询如下所示:
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]
对于Node.js中的Mongoose:
db.users.find({'name': {'$regex': '.*sometext.*'}})
MongoRegex已被弃用。
使用MongoDB \ BSON \ Regex:
$regex = new MongoDB\BSON\Regex ( '^m');
$cursor = $collection->find(array('users' => $regex));
//iterate through the cursor
如果您有字符串变量,则必须将其转换为正则表达式,因此MongoDB将对其使用类似的语句。
const name = req.query.title; //John
db.users.find({ "name": new Regex(name) });
结果与:
db.users.find({"name": /John/})
在MongoDb中,可以使用likeusingMongoDB引用运算符正则表达式(regex)。
对于相同的Ex。
MySQL - SELECT * FROM users WHERE name LIKE '%m%'
MongoDb
1) db.users.find({ "name": { "$regex": "m", "$options": "i" } })
2) db.users.find({ "name": { $regex: new RegExp("m", 'i') } })
3) db.users.find({ "name": { $regex:/m/i } })
4) db.users.find({ "name": /mail/ })
5) db.users.find({ "name": /.*m.*/ })
MySQL - SELECT * FROM users WHERE name LIKE 'm%'
MongoDb Any of Above with /^String/
6) db.users.find({ "name": /^m/ })
MySQL - SELECT * FROM users WHERE name LIKE '%m'
MongoDb Any of Above with /String$/
7) db.users.find({ "name": /m$/ })