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

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

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


当前回答

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

其他回答

对于Node.js中的Mongoose:

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

似乎有理由同时使用JavaScript/regex_pattern/模式和MongoDB{“$regex”:“regex_pattern”}模式。请参阅:MongoDB RegEx语法限制

这不是一个完整的正则表达式教程,但在看到上面一篇投票率很高的模棱两可的帖子后,我受启发运行这些测试。

> ['abbbb','bbabb','bbbba'].forEach(function(v){db.test_collection.insert({val: v})})

> db.test_collection.find({val: /a/})
{ "val" : "abbbb" }
{ "val" : "bbabb" }
{ "val" : "bbbba" }

> db.test_collection.find({val: /.*a.*/})
{ "val" : "abbbb" }
{ "val" : "bbabb" }
{ "val" : "bbbba" }

> db.test_collection.find({val: /.+a.+/})
{ "val" : "bbabb" }

> db.test_collection.find({val: /^a/})
{ "val" : "abbbb" }

> db.test_collection.find({val: /a$/})
{ "val" : "bbbba" }

> db.test_collection.find({val: {'$regex': 'a$'}})
{ "val" : "bbbba" }

您有两个选择:

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

or

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

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

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

使用JavaScript RegExp

按空格拆分名称字符串,并生成单词数组映射到迭代循环,并将字符串转换为名称中每个单词的正则表达式

let name=“My name”.split(“”).map(n=>新RegExp(n));console.log(名称);

结果:

[/My/, /Name/]

有两种情况可以匹配字符串,

$in:(类似于$or条件)

尝试在表达式中使用$。要在$in查询表达式中包含正则表达式,只能使用JavaScript正则表达式对象(即/patter/)。例如:

db.users.find({ name: { $in: name } }); // name = [/My/, /Name/]

$all:(类似于$和条件)文档应包含所有单词

db.users.find({ name: { $all: name } }); // name = [/My/, /Name/]

使用嵌套的$and和$or条件和$regex

有两种情况可以匹配字符串,

$或:(类似于$in条件)

db.users.find({
  $or: [
    { name: { $regex: "My" } },
    { name: { $regex: "Name" } }
    // if you have multiple fields for search then repeat same block
  ]
})

游戏场

$和:(类似于$all条件)文档应包含所有单词

db.users.find({
  $and: [
    {
      $and: [
        { name: { $regex: "My" } },
        { name: { $regex: "Name" } }
      ]
    }
    // if you have multiple fields for search then repeat same block
  ]
})

游戏场

您可以在MongoDB中使用正则表达式。

例如

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