0

I am trying to find the sum of all stories in my book collections that have a certain batch ID.

When I run the following pipeline,

db.getCollection("book").aggregate(
{
  '$match' : {
    active: true,
    stories:{
      $filter: { 
        input: "$stories",
           as: "story",
         cond: { $eq: [ "$$story.batch", "JUL-2018" ] }
         }
    }

  }
},
{
  '$project' : {
    count:{$size: '$stories'}
  }
}
,
{
  '$group' : {
    _id: "1",
    story_count: {$sum: '$count'}
  }
}

)

I get:

Unable to execute the selected commands

Mongo Server error (MongoCommandException): Command failed with error 2: 'unknown operator: $filter' on server 127.0.0.1:27017. 

The full response is:
{ 
    "ok" : 0.0, 
    "errmsg" : "unknown operator: $filter", 
    "code" : NumberInt(2), 
    "codeName" : "BadValue"
}

What am I doing wrong?

kratos
  • 2,465
  • 2
  • 27
  • 45
  • 1
    As demonstrated in many existing answers the `$filter` operator is for usage in a `$project` or similar "projection/alteration" stage. A `$match` stage is for "query" operators. You could use with `$expr` in modern releases, but in the context of what you are doing here it belongs inside the `$project` as the "right hand side" argument to the `$size` operator, in order to "filter matching entries" before you determine the "size". – Neil Lunn Nov 12 '18 at 00:38
  • Got it. Thank you. – kratos Nov 12 '18 at 00:48

0 Answers0