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

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

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


当前回答

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

例如

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

其他回答

下面是使用正则表达式进行字符串搜索的不同类型的要求和解决方案。

您可以使用包含单词的正则表达式,例如like。也可以使用$options=>i进行不区分大小写的搜索。

包含字符串

db.collection.find({name:{'$regex' : 'string', '$options' : 'i'}})

不包含字符串,仅包含正则表达式

db.collection.find({name:{'$regex' : '^((?!string).)*$', '$options' : 'i'}})

完全不区分大小写的字符串

db.collection.find({name:{'$regex' : '^string$', '$options' : 'i'}})

以字符串开头

db.collection.find({name:{'$regex' : '^string', '$options' : 'i'}})

以字符串结尾

db.collection.find({name:{'$regex' : 'string$', '$options' : 'i'}})

将正则表达式备忘表作为书签,并作为您可能需要的任何其他更改的参考。

如果您使用的是PHP,可以使用MongoDB数据对象包装器,如下所示:

$model = new MongoDB_DataObject();

$model->query("select * from users where name like '%m%'");

while($model->fetch()) {
    var_dump($model);
}

Or:

$model = new MongoDB_DataObject('users);

$model->whereAdd("name like '%m%'");

$model->find();

while($model->fetch()) {
    var_dump($model);
}

您可以使用MongoDB 2.6的新功能:

db.foo.insert({desc: "This is a string with text"});
db.foo.insert({desc:"This is a another string with Text"});
db.foo.ensureIndex({"desc":"text"});
db.foo.find({
    $text:{
        $search:"text"
    }
});

Use:

const indexSearch = await UserModel.find(
      { $text: { $search: filter } },
    );

    if (indexSearch.length) {
      return indexSearch;
    }
    return UserModel.find(
      {
        $or: [
          { firstName: { $regex: `^${filter}`, $options: 'i' } },
          { lastName: { $regex: `^${filter}`, $options: 'i' } },
          { middleName: { $regex: `^${filter}`, $options: 'i' } },
          { email: { $regex: `^${filter}`, $options: 'i' } },
        ],
      },
    );

我使用了正则表达式和“索引”的组合。

还可以按如下方式使用通配符过滤器:

{"query": { "wildcard": {"lookup_field":"search_string*"}}}

请务必使用*。