Home > Back-end >  Mongoose sum $size of subdocuments array field
Mongoose sum $size of subdocuments array field

Time:12-10

I have a document like this

{
 _id:ObjectId,
 subdocuments:[{
     arrayField:[String]
  }]
}

How can I get the total length of arrayFields contained in my parent document? I can get the number of subdocuments with $size : "$subdocuments", but I need something like $size : "$subdocuments.arrayField"

CodePudding user response:

I can't think of a better way, but this should work:

db.collections.aggregate(
    { $unwind: "$subdocuments" },
    { $project: {
                  "arrayFieldLength": { $strLenCP: "$subdocuments.arrayField"
                }
    });

CodePudding user response:

What I ended up doing is using the $map operator like this

{
  $addFields:{
    myLength:{
       $sum:{
           $map: {
               input: "$subdocuments.arrayField",
               as: "iterator",
               in: { $size: "$$iterator" },
                },
            }
         }
       }
}
  • Related