MongoDB: Count documents in array of nested document for a specific field in the main document

Viewed 265

i have this collection on MongoDB Collection structure

The main document has like main Field wineName. Now in this image the array of nested document (reviews) is only one but could be several reviews for each wines. My question is how can I count the number of reviews that I have for each Wine?

Thank you in advance for the answer

1 Answers

You can use the $size aggregation operator for this:

db.collection.aggregate([
  {
    "$addFields": {
      "reviewCount": {
        $size: "$reviews"
      }
    }
  }
])

Mongo Playground

Related