user1920
user1920

Reputation: 89

equal condition is not working properly in groupby mongodb

equal condition ($eq) is not working properly in mongo db. below is my mongo db document(table).

{  
"_id":ObjectId("55b08b169d735e293624504a"),
"a":[  
    {  
        "acid":139,
        "akey":"love",
        "atp":"abcd",
        "aadd":" ",
        "adur":3073
    }
],
"created":    ISODate("2015-07-23T06:35:02.959    Z")

}

My Query is

[  
{  
    "$match":{  
        "created":{  
            "$gte":                ISODate("2015-01-19T07:26:49.045                Z"),
            "$lte":                ISODate("2015-08-20T07:37:56.045                Z")
        }
    }
},
{  
    "$match":{  
        "cid":{  
            $nin:[  
                "59290C6FCCB7E82BD3861F9B6EB46930_2017dec8-0c2c-40c5-9c33-4e3ced0d692f",
                "F098F7DBEFCBAE3ED0E815DE694F2307_8fbe1abc-0d11-443d-bd0a-bf5f181673de",
                "9BAE0D8CA2A3B4BB641C8CCA2A0BD935_d7a76cf4-eb42-41f8-a851-06dd25269fbf"
            ]
        }
    }
},
{  
    "$unwind":"$a"
},
{  
    $group:{  
        _id:"$a.acid",
        "PrestoBarImpression":{  
            "$sum":{  
                "$cond":[  
                    {  
                        "$eq":[  
                            "$a.atp",
                            "abcd"
                        ]
                    },
                    "$total",
                    1
                ]
            }
        },
        "entries":{  
            $sum:1
        }
    }
}

]

I am getting the following output .

{  
"result":[  
    {  
        "_id":139,
        "PrestoBarImpression":0,
        "entries":1.0000000000000000
    }
],
"ok":1.0000000000000000

}

If I put ne instead of eq I am getting desired output as impressions are 1 and entries are 1.

Please let me know what I did mistake in the query

Upvotes: 2

Views: 3059

Answers (1)

chridam
chridam

Reputation: 103435

The $eq operator works by comparing two values and returns true when the values are equivalent, false when the values are not equivalent. Thus in your $cond operator, when the $eq operator expression evaluates to true, $cond should return a value of 1 and if the $eq expression evaluates to false then it should return 0 so that the accumulator operator $sum gives you the actual total.

As a result your $group pipeline stage should look like this:

{  
    $group: {  
        _id: "$a.acid",
        "PrestoBarImpression": {  
            "$sum": {  
                "$cond": [  
                    {  
                        "$eq": [ "$a.atp", "abcd" ]
                    },
                    1,
                    0
                ]
            }
        },
        "entries": { $sum: 1 }
    }
}

Upvotes: 3

Related Questions