Multiple $regex using $and in MongoDB
mongodb, regex, sql
Solution
Simply build proper regex
pattern "/A AND B/"
pattern "/NOT (NOT A OR NOT B)/"
Regex:
"/^(^A|^B)/"
Or this one
/(?=.*word1)(?=.*word2)/
Problem
I have some collection with the next records: ``` { "_id" : ObjectId("52b18fb2a21351b2bb29dfc7"), "title" : "aaa" } { "_id" : ObjectId("52b18fd0d17d7f69e078f7b7"), "title" : "bbb" } { "_id" : ObjectId("52b18fd3d17d7f69e078f7b8"), "title" : "ccc" } ``` Next query gives as a result 1 records (with title="aaa") as we expected: ``` db.test.find({ {title:{$regex:'aaa'}} }) ``` But when we use complex condition for $and we got something unexpected: ``` db.test.find({ $and: [ {title:{$regex:'aaa'}}, {title:{$regex:'bbb'}} ] }) ``` I need query exactly in this case because I'm going to use selection with stop-words, for example: ``` db.test.find({ $and: [ {title:{$regex:'aaa'}}, {title:{$regex:'bbb'}}, {title:{$not:/bbb/i}}, ] }) ``` Using query that above, I expecting only one field in result (with title="aaa"). I have idea how to solve this issue using aggregate, but I hope there is another way how to solve it. Thanks!