Lukáš Rutar
Lukáš Rutar

Reputation: 316

Using query as expression in aggregate

I need to use normal filter query as expression in $cond condition in aggregate.

For example use this 'condition', what would be used as filter

'$and':[{'foo':'xxx'},{'bar':'zzz'}]

as this 'condition', equivalent form that would be used in aggregation

'$and'[{'$eq':['$foo','xxx']},{'$eq':['$bar':'zzz']}]

Reason for this is that I have certain filters stored and at some point I need to test them against some documents, but because there is multiple of them, for performance reason I want to avoid doing it with multiple sequential find queries, so it could be used like this

aggregate([
    { 
        $match: { <match the document> } 
    },
    { 
        $project: {
            0: {$cond: [ <filter0>, true, false]},       
            1: {$cond: [ <filter1>, true, false]},
            2: {$cond: [ <filter2>, true, false]},
            ....
        }
    }
])

What I want to achieve by using query in $cond is guaranteed consistency of result with its use in $match or in find()

So what I need is essentially 'inverse $expr'.

Upvotes: 0

Views: 115

Answers (1)

vcode
vcode

Reputation: 453

You can use $facet to run multiple queries on same data.

aggregate([
    { 
        $match: { <match the document> } 
    },
    { 
        $facet: {
            0: [{$match: {query0}}],       
            1: [{$match: {query1}}],
            2: [{$match: {query2}}],
            ....
        }
    }
])

Upvotes: 1

Related Questions