Rakesh
Rakesh

Reputation: 178

Total number of count using aggrigate

Without $match in the following code, I am getting the result but after include $project I am getting error "Someting went wrong" by mongodb.

[
    {
      $project: {
        mydata: {
          $cond: {
            if: { $isArray: '$activities' },
            then: {
              $size: '$activities'
            },

            else: 'NA'
          }
        }
      }
    },
    { $match: { mydata: { $gt: 1 } } }
  ];

So, I need to count of all mydata which value is greater than 1.

Upvotes: 4

Views: 56

Answers (2)

Himanshu Sharma
Himanshu Sharma

Reputation: 3010

@Chridam is correct. Besides that, the following query can also do the trick:

db.collection.find({"activities.2":{$exists:true}}).pretty()

Data set:

{
    "_id" : ObjectId("5d5fe03bc90be6af447ab919"),
    "activities" : [
        1,
        2,
        3,
        4
    ]
}
{ "_id" : ObjectId("5d5fe03bc90be6af447ab91a"), "activities" : [ 1, 2 ] }
{ "_id" : ObjectId("5d5fe03bc90be6af447ab91b"), "activities" : null }
{ "_id" : ObjectId("5d5fe03bc90be6af447ab91c"), "activities" : [ ] }
{ "_id" : ObjectId("5d5fe03bc90be6af447ab91d"), "activities" : [ 1 ] }

Output:

{
    "_id" : ObjectId("5d5fe03bc90be6af447ab919"),
    "activities" : [
        1,
        2,
        3,
        4
    ]
}

We are checking if the element on the 2nd index of the activities array is present or not. It's only possible if the activities size is greater than 1.

Upvotes: 2

chridam
chridam

Reputation: 103365

Your else clause seems to be the one throwing an error since further down the pipeline you will be potentially comparing a string with a number. I would suggest giving the default a value 0 and check if that throws an error.

However, a better approach will be to to use the $expr operator as the find() query which allows you to query on computed fields:

db.collection.find({ 
    "$expr": {
        "$gt": [
            { "$size": { 
                "$cond": [ 
                    { "$isArray": "$activities" }, 
                    "$activities", 
                    []
                ]
            } },
            1
        ]
    }
}) 

Upvotes: 4

Related Questions