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

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

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


当前回答

为了以防万一,有人正在寻找一种SQL LIKE类型的查询,以查找包含字符串数组而不是字符串的键,这里是:

db.users.find({"name": {$in: [/.*m.*/]}})

其他回答

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

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

Use:

db.customer.find({"customerid": {"$regex": "CU_00000*", "$options": "i"}}).pretty()

当我们搜索字符串模式时,最好使用上面的模式,因为我们不确定大小写。

字符串yourdb={deepakparmar,dipak,parmar}

db.getCollection('yourdb').find({"name":/^dee/})

ans deepakparmar公司

db.getCollection('yourdb').find({"name":/d/})

ans deepakparmar,迪帕克

db.getCollection('yourdb').find({"name":/mar$/})

ans deepakparmar,帕尔马

如果您有字符串变量,则必须将其转换为正则表达式,因此MongoDB将对其使用类似的语句。

const name = req.query.title; //John
db.users.find({ "name": new Regex(name) });

结果与:

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

对于Node.js中的Mongoose:

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