1720

我想用 SQL 的like查询来查询一些东西:

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

如何在 MongoDB 中实现相同的目标?like我在文档中找不到操作符。

4

45 回答 45

2314

那必须是:

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

或者,类似的:

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

您正在寻找在某处包含“m”的东西(SQL 的 ' %' 运算符等同于正则表达式' ' .*'),而不是在字符串开头锚定“m”的东西。

注意: MongoDB 使用的正则表达式比 SQL 中的“LIKE”更强大。使用正则表达式,您可以创建您想象的任何模式。

有关正则表达式的更多信息,请参阅正则表达式(MDN)。

于 2010-07-22T03:57:50.930 回答
490
db.users.insert({name: 'paulo'})
db.users.insert({name: 'patric'})
db.users.insert({name: 'pedro'})

所以:

为了:

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

输出:保罗,帕特里克

为了:

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

输出:保罗,帕特里克

为了:

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

输出:佩德罗

于 2014-05-20T13:26:31.670 回答
348

  • PyMongo使用Python
  • 使用Node.js的猫鼬
  • Jongo , 使用Java
  • mgo , 使用Go

你可以做:

db.users.find({'name': {'$regex': 'sometext'}})
于 2012-10-07T17:07:24.447 回答
100

在 PHP 中,您可以使用以下代码:

$collection->find(array('name'=> array('$regex' => 'm'));
于 2011-05-13T08:36:20.157 回答
82

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

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

包含string

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

不包含string,仅使用正则表达式

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

不区分大小写string

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

从...开始string

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

结束于string

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

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

于 2016-08-11T15:39:09.747 回答
61

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

例如,

db.users.find({"name": /^m/})
于 2010-07-22T03:48:56.307 回答
47

你有两个选择:

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

或者

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

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

而关于“string”,你可以使用 like " .string. " (%string%),或者 "string.*" (string%) 和 ".*string) (%string) 例如。你可以使用正则随心所欲的表达。

于 2017-04-26T02:48:04.293 回答
41

如果使用Node.js它说你可以这样写:

db.collection.find( { field: /acme.*corp/i } );

// Or
db.collection.find( { field: { $regex: 'acme.*corp', $options: 'i' } } );

另外,你可以这样写:

db.collection.find( { field: new RegExp('acme.*corp', 'i') } );
于 2014-03-09T06:11:58.300 回答
27

您已经得到了答案,但要匹配不区分大小写的正则表达式,您可以使用以下查询:

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

i中的表示/m/i不区分大小写并.pretty()提供更漂亮的输出。

于 2014-11-21T05:39:14.720 回答
21

对于Node.js 中的Mongoose :

db.users.find({'name': {'$regex': '.*sometext.*'}})
于 2015-11-10T11:39:29.137 回答
14

您可以使用 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"
    }
});
于 2014-08-04T19:19:03.827 回答
14

Node.js项目中并使用Mongoose,使用like查询:

var User = mongoose.model('User');

var searchQuery = {};
searchQuery.email = req.query.email;
searchQuery.name = {$regex: req.query.name, $options: 'i'};
User.find(searchQuery, function(error, user) {
                if(error || user === null) {
                    return res.status(500).send(error);
                }
                return res.status(200).send(user);
            });
于 2015-08-11T09:47:18.840 回答
13

您可以使用where语句来构建任何 JavaScript 脚本:

db.myCollection.find( { $where: "this.name.toLowerCase().indexOf('m') >= 0" } );

参考:$哪里

于 2013-09-05T14:53:27.940 回答
13

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

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

(在 MongoDB Compass 中,使用"代替很重要'

于 2017-04-19T08:01:35.243 回答
12

在 Go 和mgo驱动程序中:

Collection.Find(bson.M{"name": bson.RegEx{"m", ""}}).All(&result)

结果是广受欢迎的类型的结构实例。

于 2014-03-17T21:50:16.277 回答
12

对于 PHP mongo 之类

我对 PHP mongo 有几个问题,例如. 我发现连接正则表达式参数在某些情况下会有所帮助 - PHP mongo find 字段以.

例如,

db()->users->insert(['name' => 'john']);
db()->users->insert(['name' => 'joe']);
db()->users->insert(['name' => 'jason']);

// starts with
$like_var = 'jo';
$prefix = '/^';
$suffix = '/';
$name = $prefix . $like_var . $suffix;
db()->users->find(['name' => array('$regex'=>new MongoRegex($name))]);
output: (joe, john)

// contains
$like_var = 'j';
$prefix = '/';
$suffix = '/';
$name = $prefix . $like_var . $suffix;
db()->users->find(['name' => array('$regex'=>new MongoRegex($name))]);

output: (joe, john, jason)
于 2014-09-17T20:20:45.230 回答
12

使用带有变量的模板文字也可以:

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

于 2018-06-08T06:43:22.590 回答
11

在 SQL 中,“<strong>like”查询如下所示:

select * from users where name like '%m%'

在 MongoDB 控制台中,它看起来像这样:

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

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

此外,该pretty()方法将在所有地方生成一个格式化的 JSON 结构,这样更易​​读。

于 2014-03-19T11:09:45.720 回答
10

正则表达式的处理成本很高。

另一种方法是创建文本索引,然后使用$search.

创建要使其可搜索的字段的文本索引:

db.collection.createIndex({name: 'text', otherField: 'text'});

在文本索引中搜索字符串:

db.collection.find({
  '$text'=>{'$search': "The string"}
})
于 2018-05-16T05:59:08.113 回答
9

字符串 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, 帕尔马

于 2019-07-30T11:22:00.623 回答
8

使用正则表达式匹配如下。'i' 表示不区分大小写。

var collections = mongoDatabase.GetCollection("Abcd");

var queryA = Query.And(
         Query.Matches("strName", new BsonRegularExpression("ABCD", "i")), 
         Query.Matches("strVal", new BsonRegularExpression("4121", "i")));

var queryB = Query.Or(
       Query.Matches("strName", new BsonRegularExpression("ABCD","i")),
       Query.Matches("strVal", new BsonRegularExpression("33156", "i")));

var getA = collections.Find(queryA);
var getB = collections.Find(queryB);
于 2015-12-11T07:35:49.040 回答
7

似乎有理由同时使用 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" }
于 2017-01-10T19:39:22.100 回答
6

类似的查询如下所示:

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]
于 2015-05-18T09:55:15.940 回答
5

如果你使用的是 Spring-Data MongoDB,你可以这样做:

String tagName = "m";
Query query = new Query();
query.limit(10);
query.addCriteria(Criteria.where("tagName").regex(tagName));
于 2015-04-28T10:34:23.143 回答
5

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

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

与以下结果相同:

db.users.find({"name": /John/})
于 2020-05-26T15:06:27.473 回答
4

由于 MongoDB shell 支持正则表达式,这是完全可能的。

db.users.findOne({"name" : /.*sometext.*/});

如果我们希望查询不区分大小写,我们可以使用“i”选项,如下所示:

db.users.findOne({"name" : /.*sometext.*/i});
于 2016-01-19T08:09:23.303 回答
4

如果您想在 MongoDB 中进行“喜欢”搜索,那么您应该使用$regex。通过使用它,查询将是:

db.product.find({name:{$regex:/m/i}})

有关更多信息,您还可以阅读文档 - $regex

于 2016-08-23T15:03:51.460 回答
4

使用聚合子字符串搜索(带索引!!!):

db.collection.aggregate([{
        $project : {
            fieldExists : {
                $indexOfBytes : ['$field', 'string']
            }
        }
    }, {
        $match : {
            fieldExists : {
                $gt : -1
            }
        }
    }, {
        $limit : 5
    }
]);
于 2018-01-03T19:16:55.383 回答
3

一种与类似查询等效的查找结果的方法:

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

Wherei用于不区分大小写的获取数据。

我们也可以得到结果的另一种方式:

db.collection.find({"name":/aus/})

以上将提供名称中包含aus的结果

于 2020-08-20T09:57:15.330 回答
3

您可以使用正则表达式进行查询:

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

如果字符串来自用户,也许你想在使用它之前转义字符串。这将防止来自用户的文字字符被解释为正则表达式标记。

例如,搜索字符串“A”。如果没有转义,也将匹配“AB”。在使用它之前,您可以使用一个简单replace的来转义您的字符串。我把它作为重用的功能:

function textLike(str) {
  var escaped = str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
  return new RegExp(escaped, 'i');
}

所以现在,字符串变成了不区分大小写的模式,也匹配文字点。例子:

>  textLike('A.');
<  /A\./i

现在我们准备好随时生成正则表达式:

db.users.find({ "name": textLike("m") });
于 2020-03-31T18:17:05.200 回答
3

利用:

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

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

于 2017-06-02T06:06:13.790 回答
3

利用:

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' } },
        ],
      },
    );

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

于 2021-03-08T19:42:41.413 回答
3

MongoRegex 已被弃用。

使用MongoDB\BSON\Regex

$regex = new MongoDB\BSON\Regex ( '^m');
$cursor = $collection->find(array('users' => $regex));
//iterate through the cursor
于 2017-01-27T20:06:51.047 回答
2

我找到了一个将MySQL查询转换为 MongoDB 的免费工具:http ://www.querymongo.com/

我检查了几个查询。在我看来,几乎所有这些都是正确的。据此,答案是

db.users.find({
    "name": "%m%"
});
于 2016-12-06T05:07:03.113 回答
2

有多种方法可以做到这一点。

最简单的一个:

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中找到。

于 2020-07-23T03:47:13.500 回答
2

使用 JavaScript 正则表达式

  • 按空格分割name字符串并创建一个单词数组
  • 映射到迭代循环并将字符串转换为名称中每个单词的正则表达式

let name = "My Name".split(" ").map(n => new RegExp(n));
console.log(name);

结果:

[/My/, /Name/]

匹配字符串有两种情况,

  1. $in:( $or条件类似)

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

db.users.find({ name: { $in: name } }); // name = [/My/, /Name/]
  1. $all:( 类似于$and条件)文档应包含所有单词
db.users.find({ name: { $all: name } }); // name = [/My/, /Name/]

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

匹配字符串有两种情况,

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

操场

  1. $and:( 类似于$all条件)一个文档应该包含所有单词
db.users.find({
  $and: [
    {
      $and: [
        { name: { $regex: "My" } },
        { name: { $regex: "Name" } }
      ]
    }
    // if you have multiple fields for search then repeat same block
  ]
})

操场

于 2021-02-27T09:24:59.970 回答
1

FullName like 'last' with status=='Pending' 在两个日期之间:

db.orders.find({
      createdAt:{$gt:ISODate("2017-04-25T10:08:16.111Z"),
      $lt:ISODate("2017-05-05T10:08:16.111Z")},
      status:"Pending",
      fullName:/last/}).pretty();

status== 'Pending' 和 orderId LIKE 'PHA876174':

db.orders.find({
     status:"Pending",
     orderId:/PHA876174/
     }).pretty();
于 2017-05-06T08:38:57.123 回答
1

如果您使用的是 PHP,则可以使用MongoDB_DataObject包装器,如下所示:

$model = new MongoDB_DataObject();

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

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

或者

$model = new MongoDB_DataObject('users);

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

$model->find();

while($model->fetch()) {
    var_dump($model);
}
于 2017-02-16T08:34:08.230 回答
1

在 MongoDb 中,可以像使用MongoDb 引用运算符正则表达式(regex)一样使用。

对于相同的前。

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$/ })
于 2022-02-16T04:12:37.023 回答
1

对于 Go 驱动程序:

filter := bson.M{
    "field_name": primitive.Regex{
        Pattern: keyword,
        Options: "",
    },
}
cursor, err := GetCollection().Find(ctx, filter)

在 $in 查询中使用正则表达式(MongoDB 文档:$in):

filter := bson.M{
    "field_name": bson.M{
        "$in": []primitive.Regex{
            {
                Pattern: keyword,
                Options: "",
            },
        }
    }
}
cursor, err := GetCollection().Find(ctx, filter)
于 2021-03-09T06:54:17.263 回答
0

这是使用“开始于”范例的命令:

db.customer.find({"customer_name" : { $regex : /^startswith/ }})
于 2020-04-23T12:26:12.440 回答
0

您还可以使用通配符过滤器,如下所示:

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

请务必使用*.

于 2018-07-07T10:34:27.177 回答
0

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

db.users.find({"name": {$in: [/.*m.*/]}})
于 2021-01-14T13:58:32.933 回答
0
>> db.car.distinct('name')
[ "honda", "tat", "tata", "tata3" ]

>> db.car.find({"name":/. *ta.* /})
于 2017-10-15T06:14:22.630 回答
0

前面的答案完美回答了关于核心 MongoDB 查询的问题。但是当使用基于模式的搜索查询时,例如:

{"keywords":{ "$regex": "^toron.*"}}

或者

{“关键字”:{“$regex”:“^toron”}}

在带有 @Query 注释的Spring Boot JPA 存储库查询中,使用类似以下的查询:

@Query(value = "{ keyword : { $regex : ?0 }  }")
List<SomeResponse> findByKeywordContainingRegex(String keyword);

调用应该是以下之一:

List<SomeResponse> someResponseList =    someRepository.findByKeywordsContainingRegex("^toron");

List<SomeResponse> someResponseList =    someRepository.findByKeywordsContainingRegex("^toron.*");

永远不要使用:

List<SomeResponse> someResponseList = someRepository.findByKeywordsContainingRegex("/^toron/");

List<SomeResponse> someResponseList =someRepository.findByKeywordsContainingRegex("/^toron.*/");

需要注意的重要一点:每次@Query语句中的?0字段都替换为双引号字符串。所以在这些情况下不应该使用正斜杠(/)!始终在搜索模式中使用双引号!例如,使用"^toron" or "^toron.*"/^toron/ or /^toron.*/

于 2021-02-10T21:42:25.557 回答