繁体   English   中英

如何在 Mongodb 中使用数字制作正则表达式

[英]How to make regex with number in Mongodb

我有如下数据。

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

我想使用正则表达式进行搜索以获得一些结果。
比如我放45的时候,这个搜索只有12345、4523。

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

但是当我传递像'45'这样的查询时,它说“不能将 $regex 与 Number 一起使用。”。
如何使用带有数字的正则表达式进行搜索? 非常感谢您阅读它。

正则表达式仅在被匹配的字段具有搅拌值时才能匹配,但在您的情况下 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'"
})

我在 mongoplayground 上试过。 试试看: https : //mongoplayground.net/p/8E9kGt5moAO

要了解有关 $where 工作原理的更多信息,您可以在此处查看 Mongodb 文档: 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
        ]
      }
    ]
  }
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM