1

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"

2 Answers 2

1

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

{
  $addFields:{
    myLength:{
       $sum:{
           $map: {
               input: "$subdocuments.arrayField",
               as: "iterator",
               in: { $size: "$$iterator" },
                },
            }
         }
       }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.