簡體   English   中英

如何在帶有字符串變量的 mongoDB 查詢中使用 $regex?

[英]How to use $regex in mongoDB query with string variable?

我正在嘗試使用用戶生成的字符串變量在 MongoDB 數據庫中執行簡單的通配符查詢。 例如,如果用戶搜索“Bu”,則應從數據庫中返回“Burger”和“Burger King”等內容。 我已經搜索並嘗試了幾件事,但似乎沒有任何效果。 任何幫助將不勝感激。 注意:這是客戶端 JS。

    var text = document.getElementById("Search_Box").value;

    var regex = new RegExp(text + ".*");

    client.login().then(() => db.collection('businesses')
        .find({name:{$regex:regex}}).then(docs => {
          console.log("[MongoDB Stitch] Connected to Stitch");

如果您有以下文件:

{
    "_id" : ObjectId("5a0f3a464d8a2fe38bec4e92"),
    "name" : "Burger"
}

{
    "_id" : ObjectId("5a0f3a464d8a2fe38bec4e94"),
    "name" : "Burger King"
}

{
    "_id" : ObjectId("5a0f3a464d8a2fe38bec4e96"),
    "name" : "Booby's"
}

{
    "_id" : ObjectId("5a0f3a464d8a2fe38bec4e98"),
    "name" : "McDonald"
}

從...開始

要獲得以“Bu”開頭的所有內容,您可以這樣做

db.collection('businesses').find({name: {$regex: '^Bu'}})

要么

db.collection('businesses').find({name: {$regex: /^Bu/}})

在中間

如果您需要在單詞的任何位置包含“Ki.*g”的任何內容,您可以執行以下操作:

db.collection('businesses').find({name: {$regex: 'Ki.*g'}})

要么

db.collection('businesses').find({name: {$regex: /Ki.*g/}})

努力並閱讀文檔。 一切都在那里進行了解釋,並提供了更多詳細信息。 https://docs.mongodb.com/manual/reference/operator/query/regex/

我有類似的問題。 我發送:

async search (term) {
  this.suggestions = await this.db.collection(this.collection).find({name: {$regex: term + '.*', $options: 'i'}}).sort({'_id': 1}).execute()
}

我從 Mongo 拿回了這個

Stack Trace:
StitchError: $regex requires regular expression
at find (<native code>)
at apply (<native code>)
at executeServiceFunction (<anonymous>:10:10)
{
  "service": "mongodb-atlas",
  "name": "find",
  "arguments": [
    {
      "database": "monsters",
      "collection": "monsters",
      "query": {
        "name": {
          "$regex": "Aart.*",
          "$options": "i"
        }
      },
      "project": null,
      "sort": {
        "_id": {
          "$numberInt": "1"
        }
      }
    }
  ]
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM