jingo_man
jingo_man

Reputation: 529

MongoDB Aggregation - Keeping field names

I have a collection of documents that are scores per round of golf. I am trying to:

I have everything but the last part, with this Aggregation stage:

{
  _id: "$playerName",
  total: {
    $sum: "$total"
  },
  rounds: { $push: "$holes" }
}

I don't know how to add extra fields to this stage keeping the courseId value from each source document. I have seen $$ROOT but I don't need everything.

When I do this, rounds is an Array of Objects, as:

{
  "_id" : "Tiger Woods",
  "total" : 45
  "rounds" : {
    0 : { { 1 : 2 }, { 2: 2 }, ... },
    1 : { ... },
    2 : { ... }
  }
}

round sub-doc structure

I would like to put in the key name part of the above array with the courseId value, so it can be used later - or any other way to reference it:

{
  "_id" : "Tiger Woods",
  "total" : 45
  "rounds" : {
    "course1" : { ... },
    "course2" : { ... },
    "courseN" : { ... }
  }
}

The original document structure is - there is 1 document "per comp per course" played:

{
    "compId": "607019361c071256e4f0d0d5",
    "courseId": "608952e3abebbd503ba6e115",
    "playerId": "609d0993906429612483cea0",
    "holes": {
        "1": 2,
        "2": 1,
        "3": 2,
        "4": 2,
        "5": 2,
        "6": 2,
        "7": 0,
        "8": 2,
        "9": 3
    },
    "playerName": "Tiger Woods",
    "total": 16
}

I need to reference which courseId with each rounds array element. I thought it might be the key part of the key/value pair but I can only name the whole Array as "rounds"

Or maybe it's because the original holes is an Object, not an Array? How would I change this?

Upvotes: 1

Views: 558

Answers (1)

varman
varman

Reputation: 8894

You can use $group the $arrayToObject

  • when you $group it, you can make it as key value pair(k,v). By using the $arrayToObject u can get the desired outpur

Here is the code

db.collection.aggregate([
  {
    "$group": {
      _id: "$playerName",
      total: { $sum: "$total" },
      rounds: {
        $push: {
          k: "$courseId",
          v: "$holes"
        }
      }
    }
  },
  {
    $addFields: {
      rounds: { "$arrayToObject": "$rounds" }
    }
  }
])

Working Mongo playground

Upvotes: 2

Related Questions