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

Time:08-04

I have the following document structure

_id:2
lines:Array

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

CodePudding user response:

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" }
  }
}
  • Related