RyanJLeonard
RyanJLeonard

Reputation: 11

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

I am trying to do a simple wildcard query in a MongoDB database using a user-generated string variable. For example, if the user searches 'Bu', things like 'Burger' and 'Burger King' should be returned from the database. I have searched and tried several things but nothing seems to work. Any help would be greatly appreciated. Note: This is client-side 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");

Upvotes: 1

Views: 11470

Answers (2)

RakMaster
RakMaster

Reputation: 1

I'm having a similar problem. I'm sending:

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

And I'm getting this back from 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"
        }
      }
    }
  ]
}

Upvotes: -1

Alex P.
Alex P.

Reputation: 3171

If you had the following documents:

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

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

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

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

Starting with

To get everything starting with "Bu" you could do

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

or

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

In the middle of

If you needed anything that contained "Ki.*g" anywhere in the word you could do:

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

or

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

Do the effort and go through the documentation. Everything is explained there, with a lot more details. https://docs.mongodb.com/manual/reference/operator/query/regex/

Upvotes: 5

Related Questions