mongodbaggregation-framework

MongoDB error : Pipeline stage specification object must contain exactly one field


I am new to mongodb and trying out aggregation.

 db.aggregate([
  { '$match': {} },
  {
    '$group': { _id: [Object] },
    '$project': {
      resource_subcategory: '$_id.resource_subcategory',
      resource_usage: 1
    }
  }
])

I get the error:

A pipeline stage specification object must contain exactly one field.

I couldn't find a good explanation of the reason in SO.


Solution

  • It should be like this:

    db.aggregate([
      { '$match': {} },
      { '$group': { _id: [Object] } },
      { '$project': {
          resource_subcategory: '$_id.resource_subcategory',
          resource_usage: 1
        }
      }
    ])
    

    However { '$match': {} } is pointless, it selects all documents. You can skip it.

    resource_usage is not part of group accumulator, thus it will be always empty, i.e. it's also pointless.