简体   繁体   中英

$regex to find whole words, mongodb

Find items containing a whole word.

const queryparam = 'microsoft';

mongoose.model('tag').find({name: { $regex:  new RegExp("\w"+queryparam+"\w" ), '$options': 'i' }});

// tag collection

    [
      {
         name: 'Microsoft word" // this should be returned by query
      },
      {
         name: 'Microsoft-word" // this should not be returned by query
      }
    ]

It's not working.

Try this (thanks to @Toto):

db.tag.find({
  name: {
    "$regex": "\\bMicrosoft\\b\\s",
    "$options": "i"
  }
})

MongoPlayground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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