0

I want to search a mongo database with a RegExp, but instead of returning data with the matched RegExp I want to return data that does not have the RegExp.

For example:

Find all data that does not contain a new RegExp("mediaType").

I have really bad knowledge of RegExp so I'm not sure how to go about this.

Taylor Austin
  • 5,407
  • 15
  • 58
  • 103
  • I came across this pattern [^((?!badword).)*$](https://www.regextester.com/15). I cannot explain it hence why I leave it as a comment. – Mikey Jan 03 '18 at 16:28
  • 1
    @Mikey that is a [tempered greedy token](https://stackoverflow.com/questions/30900794/tempered-greedy-token-what-is-different-about-placing-the-dot-before-the-negat). It matches any character `.` until it finds `badword`, then it stops. – ctwheels Jan 03 '18 at 16:29
  • @ctwheels Good know! – Mikey Jan 03 '18 at 16:30
  • @ctwheels is it okay to use ? – Taylor Austin Jan 03 '18 at 16:30
  • 1
    @TaylorAustin it is ok to use but I'm sure there are better ways. I'm not too familiar with mongodb, unfortunately, so my help is limited here. [This question](https://stackoverflow.com/questions/20175122/how-can-i-use-not-like-operator-in-mongodb) contains relevant information for what you're trying to accomplish though – ctwheels Jan 03 '18 at 16:33

1 Answers1

3

To find elements matching a regexp (e.g. pattern) you can use:

db.coll.find({ fieldName: { $regex: /pattern/ } });

To find elements NOT matching the same regexp you can use:

db.coll.find({ fieldName: { $not: /pattern/ } });
Marcello
  • 879
  • 6
  • 20
  • so would `db.coll.find({ description: {$not: /mediaType/ })` find me all data with description not containing `"mediaType"` ? – Taylor Austin Jan 03 '18 at 16:35
  • @TaylorAustin you should be able to use `/mediaType/` but you may want to use `/^.*mediaType/` instead (not sure which will perform better - depends on your data) – ctwheels Jan 03 '18 at 16:36
  • 1
    @TaylorAustin `^` anchors the pattern to the start of the line and `.*` matches any character (except newline `\n`) any number of times. But you should also just be able to use `mediaType` – ctwheels Jan 03 '18 at 16:38