Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 !

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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" }
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading