Home > other >  Is it possible to use $size with a condition?
Is it possible to use $size with a condition?

Time:09-16

Is it possible to use the $size operator when sub-docs meet a specific condition?

Here is the example doc:

{
   likes: [{
     like: true,
     username: 'bob'
   }, {
     like: false,
     username: 'tim'
   }]
   ..... other attributes
}

Is it possible to query the docs and $set a count for the likes where like is true?

'$set': {
  'likeCount': {
    $size: '$likes',
  },
},

The above will return likeCount as 2 from the example doc

But what i would like to do is return a count of the docs where like is true, ie:

'$set': {
  'likeCount': {
    $size: {
      '$likes': {
        like: true
      }
    },
  },
},

But i just get an error:

MongoError: Invalid $set :: caused by :: Unrecognized expression '$likes'

CodePudding user response:

Test code here

Query

db.collection.aggregate([
  {
    "$set": {
      "true-like-count": {
        "$size": {
          "$filter": {
            "input": "$likes",
            "cond": "$$this.like"
          }
        }
      }
    }
  }
])

CodePudding user response:

You can use $filter in a $project stage like this to have only values where your condition is match:

db.collection.aggregate([
  {
    "$project": {
      "likes": {
        "$filter": {
          "input": "$likes",
          "as": "l",
          "cond": {
            "$eq": [
              "$$l.like",
              true
            ]
          }
        }
      }
    }
  },
  {
    "$set": {
      "likeCount": {
        $size: "$likes"
      }
    }
  }
])

Example here

Also if you don't want to loose the array likes you can create an auxiliar value like this example

  • Related