Martin Gunnarsson
Martin Gunnarsson

Reputation: 186

MongoDB $or acting like $and

I'm trying to count the number of documents having either a non-empty features array or a non-empty description string like so:

collection.find({
    $or: [{
        features: {$exists: true, $not: {$size: 0}},
        description: {$exists: true, $ne: ""}
    }],
}).count()

Weirdly enough (to me), adding the second expression to the $or array reduces the number of matches. 556 documents have a non-empty featuresarray, and 294 have a non-empty description. Combining the two using $or results in 214 matches, and they all seem to have both description and features. What am I missing here?

Upvotes: 1

Views: 141

Answers (1)

Đăng Khoa Đinh
Đăng Khoa Đinh

Reputation: 5411

It's because your 2 conditions are in the same item of the $or array. So basically, you're filtering for documents satisfy both conditions. I think the second condition should be in the second item of the array, like this :

collection.find({
    $or: [
    {
        features: {$exists: true, $not: {$size: 0}},
       
    }, 
    {
        description: {$exists: true, $ne: ""}
    }
],
}).count()

Upvotes: 3

Related Questions