Home > Software design >  MongoDB Counting Unique Attributes
MongoDB Counting Unique Attributes

Time:10-28

I currently have objects in MongoDB that are laid out in the following format.

{
    _id: new ObjectId("6179a02db235317ce6511429"),
    song: 'BIBLICAL',
    artist: 'CALUM SCOTT',
    expProg: 'Autoplay',
    actProg: 'Autoplay',
    playedAt: 1635360813
  },
  {
    _id: new ObjectId("6179a117b235317ce651142a"),
    song: 'WILL YOU STILL LOVE ME?',
    artist: 'CHICAGO',
    expProg: 'Autoplay',
    actProg: 'Autoplay',
    playedAt: 1635361047
  },
  {
    _id: new ObjectId("6179a20cb235317ce651142b"),
    song: 'SHY GUY',
    artist: 'DIANA KING',
    expProg: 'Autoplay',
    actProg: 'Autoplay',
    playedAt: 1635361292
  }

I was wondering how the aggregation pipeline would look if I wanted to count the occurrence of each individual song on my database?

In this case what I would want returned would be something like

'BIBLICAL' : 1
'WILL YOU STILL LOVE ME?' : 1
'SHY GUY' : 1

Thanks!

CodePudding user response:

Yes, it is possible and so easy, only using $group stage and $sum 1.

Also to get the value for each song as key you can use $replaceRoot with $arrayToObject.

db.collection.aggregate([
  {
    "$group": {
      "_id": "$song",
      "count": {
        "$sum": 1
      }
    }
  },
  {
    "$replaceRoot": {
      "newRoot": {
        "$arrayToObject": [
          [
            {
              "k": "$_id",
              "v": "$count"
            }
          ]
        ]
      }
    }
  }
])

Example here

Output is like this:

[
  {
    "BIBLICAL": 1
  },
  {
    "SHY GUY": 1
  },
  {
    "WILL YOU STILL LOVE ME?": 1
  }
]
  • Related