I have a collection and each document in that collection has an array field countries. I want to select all documents which include any of below countries:
China, USA, Australia
And the output should show the number of above countries each document has. I use below aggregate command:
db.movies.aggregate([
{
$match: { countries: { $in: ["USA", 'China', 'Australia'] } }
},
{
$project: {
countries: {$size: '$countries'}
}
}
]);
it doesn't work as expected. It shows the number of all countries in the document who has the above-listed country. For example, if a document has China, Japan in its countries field, I expected it return 1 (because only China is in the above country list) but it returns two. How can I do that in the aggregation command?