Filter documents with a property that can be or true or null MongoDB

Viewed 169

I have this query:

collection.aggregate([
    { $match:{ "card.discovery": true } }
    { $sample: { size: 4 } }
]);

And it works because I need to get 4 random entries from that collection, but card.discovery can be true or null, and this obviously only returning documents with card.discovery set to true.

How can I filter the documents so that card.discovery can be or true or null?

3 Answers

You can take advantage of the $in operator:

{ $match: { "card.discovery": { $in: [ true, null ] } } }

Mongo Playground

You can use the $in operator:

collection.aggregate([
    { $match: { "card.discovery": { $in: [null, true] } } },
    { $sample: { size: 4 } }
]);

Alternatively, you can use the $or operator:

collection.aggregate([
    { $match: { $or: ["{card.discovery": true }, {"card.discovery": null}] } },
    { $sample: { size: 4 } }
]);

Try this $or option

collection

[{ 
    "_id" : 1.0, 
    "card" : {
        "discovery" : true
    }
}
{ 
    "_id" : 2.0, 
    "card" : {
        "discovery" : null
    }
}
{ 
    "_id" : 3.0, 
    "card" : {
        "discovery" : true
    }
}
{ 
    "_id" : 4.0, 
    "card" : {
        "discovery" : true
    }
}
{ 
    "_id" : 5.0, 
    "card" : {
        "discovery" : null
    }
}
{ 
    "_id" : 6.0, 
    "card" : {
        "discovery" : false
    }
}
{ 
    "_id" : 7.0, 
    "card" : {
        "discovery" : false
    }
}]

Query

db1.aggregate([
        { $match: { $or: [{ "card.discovery": true }, { "card.discovery": null }] }, },
        { $sample: { size: 4 } }
    ]).toArray();

Output

[
        {
            "_id": 4,
            "card": {
                "discovery": true
            }
        },
        {
            "_id": 1,
            "card": {
                "discovery": true
            }
        },
        {
            "_id": 3,
            "card": {
                "discovery": true
            }
        },
        {
            "_id": 5,
            "card": {
                "discovery": null
            }
        }
    ]
}]
Related