1

Sample Doc :


{
    "id": "K",
    "powers": [
        {
            "label": "a",
            "Rating": 7
        },
        {
            "label": "b",
            "Rating": 3
        },
        {
            "label": "c",
            "Rating": 4
        },
        {
            "label": "d",
            "Rating": 5
        }
    ],
    "phy": {
        "height": 67,
        "weight": 150
    }
}

For this collection, I want to count how many distinct powers each id has.

I want the result as - ID =K, distinct power label - 4

whoami - fakeFaceTrueSoul
  • 17,086
  • 6
  • 32
  • 46
kbs
  • 51
  • 1
  • 5

1 Answers1

0

So the easiest way to get it done is

/** db.collection.distinct('field on which distinct is needed', condition) */

db.collection.distinct('powers.label', {"id" : "K"})

As it will be an array, You can do .length in code to get the unique length.

Ref : .distinct()

whoami - fakeFaceTrueSoul
  • 17,086
  • 6
  • 32
  • 46