6

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!

2 Answers 2

5

Simply build proper regex

pattern "/A AND B/"
pattern "/NOT (NOT A OR NOT B)/"

Regex:

"/^(^A|^B)/"

Or this one

/(?=.*word1)(?=.*word2)/
Sign up to request clarification or add additional context in comments.

1 Comment

I believe that using regexs like these I will have troubles with perfomance. Also, another similar way - use $where. But if I will have more than 10kk records in table, then time for executing that query will goes to lightly infinity..
1

Well, tested using another data and got expected result:

/* 0 */
{
    "_id" : ObjectId("52b18fb2a21351b2bb29dfc7"),
    "title" : "aaa"
}

/* 1 */
{
    "_id" : ObjectId("52b18fd0d17d7f69e078f7b7"),
    "title" : "bbb"
}

/* 2 */
{
    "_id" : ObjectId("52b18fd3d17d7f69e078f7b8"),
    "title" : "ccc"
}

/* 3 */
{
    "_id" : ObjectId("52b19606d17d7f69e078f7b9"),
    "title" : "aaa test"
}

/* 4 */
{
    "_id" : ObjectId("52b19624d17d7f69e078f7ba"),
    "title" : "aaa test wel"
}

Query:

db.test.find({
    $and: [
        {title:{$regex:'aa'}},
        {title:{$regex:'t'}},
        {title:{$not:/wel/}}
    ]
})

Response:

/* 0 */
{
    "_id" : ObjectId("52b19606d17d7f69e078f7b9"),
    "title" : "aaa test"
}

Perhaps, that issue reproducing only when title and conditions contains cyrillic symbols. Going to to reproduce it now..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.