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

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

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


当前回答

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

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

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

其他回答

db.users.insert({name: 'patrick'})
db.users.insert({name: 'petra'})
db.users.insert({name: 'pedro'})

因此:

For:

db.users.find({name: /a/})  // Like '%a%'

输出:patrick,petra

For:

db.users.find({name: /^pa/}) // Like 'pa%'

输出:patrick

For:

db.users.find({name: /ro$/}) // Like '%ro'

输出:pedro

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

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

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

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

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

有多种方法可以实现这一点。

最简单的一个:

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

{ <field>: { $regex: /pattern/, $options: '<options>' } }
{ <field>: { $regex: 'pattern', $options: '<options>' } }
{ <field>: { $regex: /pattern/<options> } }

db.users.find({ "name": { $regex: "m"} })

更多详细信息可以在$regex中找到。

In

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

您可以执行以下操作:

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