1

there are some data in mongodb:

{'name': 'bob', age: 12}
{'name': 'sam': age: 34}
{'name': 'byaelle': age: 22}

if I want to get the data of name include am
I can use

{'name': {'$regex': 'am'}}

But, how can I get the data of name exclude am?

Community
  • 1
  • 1
nataila
  • 1,549
  • 4
  • 18
  • 25

2 Answers2

7

Of course you can just reverse with $not:

db.collection.find({ "name": { "$not": /am/  } })

But since it's a $regex you can just do this:

db.collection.find({ "name": /^((?!am).)*$/ })

Or

db.collection.find({ "name": { "$regex": "^((?!am).)*$", "$options": "gm" } })

Making sure that the content matches over multiple lines if your string is formed that way.


For multiple fragments to exclude you can separate them in the expression using |. For example to exclude words containing "bo" or "am":

db.collection.find({ "name": { "$regex": "^((?!bo|am).)*$", "$options": "gm" } })

Or use the $nin operator ( "not" $in ) which accepts regular expressions:

db.collection.find({ "name": { "$nin": [/bo/,/am/] } })
styvane
  • 59,869
  • 19
  • 150
  • 156
Blakes Seven
  • 49,422
  • 14
  • 129
  • 135
1

You need to use the $not operator with a regular expression objects because $not cannot have a $regex

db.collection.find( { "name": { "$not" : /am/ }})

You can also use the following regex ^((?!am).)*$ to match text that doesn't contain a word.

collection.find({ 'name': { '$regex': '^((?!am).)*$' }})
Community
  • 1
  • 1
styvane
  • 59,869
  • 19
  • 150
  • 156