Py学习  »  MongoDB

如何在Mongodb中生成带数字的regex

DD DD • 4 年前 • 765 次点击  

我有如下数据。

[
  { num: 123, name: 'good'},
  { num: 12345, name: 'hey'},
  { num: 4523, name: 'yo' },
  { num: 777, name: 'hihi' }
]

我想用regex搜索得到一些结果。

a.find({num: {$regex: req.query.q}, name: 'yo'})

但当我传递像“45”这样的查询时,它会说“不能使用带数字的$regex”。
如何使用带数字的regex进行搜索?非常感谢您阅读。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/56929
 
765 次点击  
文章 [ 1 ]  |  最新文章 4 年前
Anuj Pancholi
Reply   •   1 楼
Anuj Pancholi    4 年前

Regex只能在所匹配的字段具有stirng值时匹配,但num在您的示例中是一个数字。

它在Mongodb文档中这样说: https://docs.mongodb.com/manual/reference/operator/query/regex/#op._S_regex

但是,有一个使用“$where”的解决方案,您可以在其中执行Javascript以返回布尔值。

db.collection.find({
  $where: "/45/.test(this.num) && this.name==='yo'"
})

我在蒙古人的地盘上试过。 试试看: https://mongoplayground.net/p/8E9kGt5moAO

https://docs.mongodb.com/manual/reference/operator/query/where/#where

还有一种方法可以在不使用$where的情况下完成此操作(在MongoDb 4.2中):

db.collection.find({
  $expr: {
    $and: [
      {
        $regexMatch: {
          input: {
            $toString: "$num"
          },
          regex: "45"
        }
      },
      {
        $gte: [
          "$time",
          12350
        ]
      },
      {
        $lt: [
          "$time",
          12400
        ]
      }
    ]
  }
})