1

I'm trying to count distinct values in sub array per document. So far I'm getting totals. My collection:

[
  {
    "_id": "5e013ca474082f6852",
    "name": [
      {
        "value": "Oak",
        "date": "2020-01-01 00:10:57"
      }
    ],
    "colors": [
      {
        "nice": "bla bala",
        "color": "Blue"
      },
      {
        "nice": "bla bala",
        "color": "Red"
      },
      {
        "nice": "bla bala",
        "color": "Blue"
      },
      {
        "nice": "bla bala",
        "color": "Green"
      },
      {
        "nice": "bla bala",
        "color": "Green"
      }
    ]
  },
  {
    "_id": "57689a4740857bb2",
    "name": [
      {
        "value": "Cloud",
        "date": "2020-01-01 00:10:57"
      }
    ],
    "colors": [
      {
        "nice": "bla bala",
        "color": "Blue"
      },
      {
        "nice": "bla bala",
        "color": "Blue"
      },
      {
        "nice": "bla bala",
        "color": "Blue"
      },
      {
        "nice": "bla bala",
        "color": "Green"
      },
      {
        "nice": "bla bala",
        "color": "Green"
      }
    ]
  }
]

The result I'm searching for is:

[
  {
    "_id": "5e013ca474082f6852",
    "name": [
      {
        "value": "Oak",
        "date": "2020-01-01 00:10:57"
      }
    ],
    "colors": {
      "Blue": 2,
      "Red": 1,
      "Green": 2
    }
  },
  {
    "_id": "57689a4740857bb2",
    "name": [
      {
        "value": "Cloud",
        "date": "2020-01-01 00:10:57"
      }
    ],
    "colors": {
      "Blue": 3,
      "Green": 2
    }
  }
]

Thanks P.S. I did not put any of my tries with aggregation using $group, because so far what I got is useless :) P.P.S. I do not know what else to say about my issue, SO says it is too much code, not enough text.

1 Answer 1

1

You can use below aggregation

db.collection.aggregate([
  { "$addFields": {
    "colors": {
      "$arrayToObject": {
        "$map": {
          "input": { "$setUnion": ["$colors.color"] },
          "as": "m",
          "in": {
            "k": "$$m",
            "v": {
              "$size": {
                "$filter": {
                  "input": "$colors",
                  "as": "d",
                  "cond": { "$eq": ["$$d.color", "$$m"] }
                }
              }
            }
          }
        }
      }
    }
  }}
])

MongoPlayground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.