Carmel Baumel-Ezra
Carmel Baumel-Ezra

Reputation: 305

Mongodb - $cond inside $match

I'm trying to write an aggregation query with MongoDB that uses $cond inside a $match. I would not detail all the considerations, only mention that the query is being dynamically effected from parameters that the user enters and thus the query is not so naive:

var anyMember = 'false';
db.PromotionLogRecord.aggregate({
    $match: {
        toSubscriberId: { 
            $cond: {
                if: {$expr:{$eq:[anyMember, 'true']}}, 
                then: ObjectId('000000000000000000000000'), 
                else: ObjectId('5cbc37583192ba000766a1e7')
            }}}},
 {$project:{'ID':'_id'}})

--> This query returns nothing, while this query returns results:

 db.PromotionLogRecord.aggregate(
     {$match: {toSubscriberId: ObjectId('5cbc37583192ba000766a1e7')}},
     {$project:{'ID':'_id'}
 })

(The original query is more complicated than this, but if I resolve why this doesn't work, I'll make a huge progress).

Am I doing something wrong? Is it possible to use $cond inside $match?

Thanks Carmel

Upvotes: 1

Views: 982

Answers (1)

Tom Slabbaert
Tom Slabbaert

Reputation: 22296

It is possible but you need to work some syntax magic:

var anyMember = 'false';
db.PromotionLogRecord.aggregate([
    {
        $match: {
            $expr: {
                $eq: [
                    "$toSubscriberId",
                    {
                        $cond: [
                            {$eq: [anyMember, 'true']},
                            ObjectId('000000000000000000000000'),
                            ObjectId('5cbc37583192ba000766a1e7')
                        ]
                    }
                ]
            }
        }
    },
    {
        $project: {
            'ID': '_id'
        }
    }
])

Upvotes: 2

Related Questions