簡體   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