1

I have to do some aggregation and I have to count into a new key value, the number of elements from an array that appears in said document, for example, if i had a list of actors, the answer would be the number of actors from this list that appears in one movie. could be all of them or just one.

I'm not sure if i should be using the $count or what.

2
  • So, you want to find the size of an array, isn't it? Commented Jan 15, 2018 at 5:20
  • Could you post some sample documents and your expected output from the sample? Commented Jan 15, 2018 at 9:05

1 Answer 1

1

You should need to find the intersection and get the size of the array.

$setIntersection will accept arrays as input and return the matching elements in an array,so one array would be your search array and another would be the one from the document, once get the intersection get count using $size

db.movies.aggregate(
   [
      {
         $project: {
            actorsCount: { $size: { $setIntersection : [$searchArray, $actor] } }
         }
      }
   ]
)
Sign up to request clarification or add additional context in comments.

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.