Issues with stages in aggregation in Compass

I am not sure I am using the stages in Compass aggregation correctly. My first stage, under projection, is:
/**

  • specifications: The fields to
  • include or exclude.
    */
    {
    doc_size: { $bsonSize: “$$ROOT”}
    }

which produces a result of the sizes of the documents in my database. I am then applying another stage, also under projection:

/**

  • specifications: The fields to
  • include or exclude.
    */
    {
    avg_doc_size: {$avg: doc_size}
    }

From what I understand from the documentation, the doc_size in the second stage should use the doc_size from the first stage. But, it appears that doc_size is not visible in the second stage. Also, I am getting an error, that the second stage is not formatted correctly, which I am assuming is because doc_size is not being recognized. What is the issue here?

In your second $project, it should be:

{
  avg_doc_size: {$avg: '$doc_size'}
}

However, I think the pipeline you want is probably

[{$project: {
  doc_size: { $bsonSize: '$$ROOT'}
}}, {$group: {
  _id: null,
  avg_doc_size: {
    $avg: '$doc_size'
  }
}}]

where the second stage is a $group and calculates the average doc size across all the docs in the collection.

1 Like

thanks, that worked!

1 Like