shiv
shiv

Reputation: 393

Conditionally Filter Documents in MongodDb

I have to do this in aggregation pipleline. I have two fields that have to be used to decide if document can be included or not.

First is agentType- may have value 1 or 2. Second is agentImage - key may exist or not.

What I am looking for is something like this.

if (agentType === 1 && agentImage not Exists) -> Filter out, If (agentType === 2) -> Keep document

For agentType === 2 i want all documents irrespective of agentImage being there or not.

Sample documents-

{agentType: 1, agentImage: "abc"}
{agentType: 2}
{agentType: 1, location: 'temp'}
{agentType: 2, agentImage: "xyz"}

In this scenario the result should be-

{agentType: 1, agentImage: "abc"}
{agentType: 2}
{agentType: 2, agentImage: "xyz"}

db.getCollection('agents').aggregate([{"$match":{agentImages: {'$exists':{'$or':[{$and:[{$eq:{'agentType': 1}},{$ne: {'agentImages': null}}]},{$eq: {'agentType': 2}}]}}}}])

This does not work, it filters out all documents with agentType 2 and with agentImage not there.

Upvotes: 3

Views: 2737

Answers (1)

chridam
chridam

Reputation: 103445

You can use the $or logic operator for this:

db.getCollection('agents').aggregate([
    {
        "$match": {
            "$or": [
                { "agentImage": { "$exists": true } },
                { "agentType": 2 }
            ]
        }
    }
])

or with find() as

db.getCollection('agents').find({           
    "$or": [
        { "agentImage": { "$exists": true } },
        { "agentType": 2 }
    ]           
})

Upvotes: 2

Related Questions