0
db.artists.insertMany([
  { "_id" : 1, "achievements" : {"third_record":true, "second_record": true} },
  { "_id" : 3, "achievements" : {"sixth_record":true, "second_record": true} },
  { "_id" : 2, "achievements" : {"first_record":true, "fifth_record": true} },
  { "_id" : 4, "achievements" : {"first_record":true, "second_record": true} },
])

I would like to count how many first_record, second_record, etc achievements have been obtained, I don't know beforehand the names of the achievements. I just want it to count all the achievements matched in the first stage. How do I use aggregation to count this? I saw another question suggest using unwind but that seems to be for arrays only and not objects?

1 Answer 1

1

May be this:

db.collection.aggregate([
  {
    $project: {
      as: {
        $objectToArray: "$achievements"
      }
    }
  },
  {
    $unwind: "$as"
  },
  {
    $group: {
      _id: "$as.k",
      number: {
        $sum: {
          "$cond": [
            {
              $eq: [
                "$as.v",
                true
              ]
            },
            1,
            0
          ]
        }
      }
    }
  }
])

Idea

  1. convert object to array
  2. unwind to get them separate
  3. group by id, adding 1 for true, 0 for false.
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.