MongoDB: How to count number of values in key
Demo - https://mongoplayground.net/p/ke3VJIErhvb
use $size to get records with 2 number of type
The $size operator matches any array with the number of elements specified by the argument. For example:
db.collection.find({ type: { "$size": 2 } // match document with type having size 2}, { name: 1 } // projection to get name and _id only )
To get the length of the array you should use $size
operator in $project
pipeline stage
So the pipeline $project stage should look like this
{ "$project": { "name": "$name", type: { "$size": "$type" } }}
Here is an working example of the same ⇒ https://mongoplayground.net/p/BmS9BGhqsFg