Harry
Harry

Reputation: 55029

Mongodb aggregation count by nested object key

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?

Upvotes: 0

Views: 304

Answers (1)

user12582392
user12582392

Reputation:

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.

Upvotes: 1

Related Questions