Count the number of elements for a nested array in Atlas Mongo pipeline

I have the following document structure


I want to retrieve the number of lines items for each document

  _id: "$_id",
  numberLines: {
    $size: "$lines"

It doesn’t work !

enter image description here

Then I want get the total lines items for the entire documents using Aggregation Pipelines

>Solution :

Group only allows accumulators operations, and $size is not one of those.

However it seems you just need to use the $project or $addFields stage as you’re not really $grouping anything.

like so:

  $project: {
     _id: 1,
     numberLines: { $size: "$lines" }

Leave a Reply