Simon Simon - 5 months ago 9
Javascript Question

How to exclude a document if two fields are the same?

After performing some aggregation magic, I have arrived at this data:

{ "_id" : "5700edfe03fcdb000347bebb", "size" : 3, "count" : 2 }
{ "_id" : "5700edfe03fcdb000347bebf", "size" : 2, "count" : 2 }


Now, I want to eliminate all the entries where size is equal to count.

So I ran this aggregation instruction:

match3 = { "$match" : { "size" : { "$ne" : "count"} } }


But it doesn't eliminate anything and returns the two lines as it is.

I want the result to be just this one line as it is the only one where size is not equal to count:

{ "_id" : "5700edfe03fcdb000347bebb", "size" : 3, "count" : 2 }

Answer

You need to add a $redact stage to your aggregation pipeline:

{ "$redact": {
    "$cond": [ 
        { "$eq": [ "$size", "$count" ] },
        "$$PRUNE",
        "$$KEEP"
    ]
}}
Comments