Bryan Migliorisi
Bryan Migliorisi

Reputation: 9210

$and query returns no result

Ok this one is killing me. Maybe its late and I am forgetting something, but this should work.

For test purposes, I have about 6000 documents in my collection. There is a property called Priority which has a value of 2 in every instance.

The following two queries each return all 6000 documents:

{
    Priority: {
        $gt: 1
    }
}

and

{
    Priority: {
        $lt: 10
    }
}

This query, however, returns 0 results and according to the Explain, does a full scan of all 6000 documents:

{
$and: [
        {
            Priority: {
                $gt: 1
            }
        },
        {
            Priority: {
                $lt: 10
            }
        }
    ]
}

Have I missed something?

Upvotes: 1

Views: 500

Answers (2)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230521

You should not use $and here.

Instead you can rewrite your query like this:

{Priority: {$gt: 1, $lt: 10}}

Upvotes: 2

David Schwartz
David Schwartz

Reputation: 182827

If I said, "I need someone with a car that can seat four people and a car that can seat at least eight people", someone with a single car that sat eight people would not ordinarily be understood to qualify. Your and query can only be satisfied by an entry with two values for Priority, one less than 10 and one greater than 1.

The docs for and have a link to the multikey semantics of mongoDB.

Upvotes: 4

Related Questions