MongoDB: How to count number of values in key

Viewed 97

I'm very new to MongoDB and I need help figuring out how to perform aggregation on a key in MongoDB and use that result to return matches.

For example, if I have a collection called Fruits with the following documents:

{
    "id": 1,
    "name": "apple",
    "type": [
      "Granny smith",
      "Fuji"
    ]
  }, {
    "id": 2,
    "name": "grape",
    "type": [
      "green",
      "black"
    ]
  }, {
    "id": 3,
    "name": "orange",
    "type": [
      "navel"
    ]
  }

How do I write a query that will return the names of the fruits with 2 types, ie apple and grape?

Thanks!

2 Answers

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

Related