Search code examples
mongodbpymongonativeaggregation

how to monogo aggregate and make certain changes to its output


I have some documents like this and we need certain changes to its output

"gameId": "string",
"markets": {

 "market X": {
    "instagram": "string",
    "lastVersion": 0,
    "market": "market X",
    "name": "string",
    "supportedVersion": 0,
    "telegram": "string",
    "config":{"A":1,"B":2 , "C":"c" }

  },
  "market Z":{
    "instagram": "string",
    "lastVersion": 0,
    "market": "market Z",
    "name": "string",
    "supportedVersion": 0,
    "telegram": "string",
    "config":{"D":5,"E":8 , "F":"vb" }
  }
}

and I want write a monogo aggregate make the output as follows

[
  {
    "gameId": "string",
    "instagram": "string",
    "lastVersion": 0,
    "market": "string",
    "name": "string",
    "supportedVersion": 0,
    "telegram": "string"
  },
  {
    "gameId": "string",
    "instagram": "string",
    "lastVersion": 0,
    "market": "string",
    "name": "string",
    "supportedVersion": 0,
    "telegram": "string"
  }
]

I tried to get the right answer but it didn't work What do you think I should do?


Solution

  • This aggregation pipeline produces your desired output from your example document.

    db.collection.aggregate([
      {
        "$addFields": {
          "x": {
            "$map": {
              "input": {
                "$objectToArray": "$markets"
              },
              "in": "$$this.v"
            }
          }
        }
      },
      {
        "$unset": "x.config"
      },
      {
        "$addFields": {
          "x.gameId": "$gameId"
        }
      },
      {
        "$unwind": "$x"
      },
      {
        "$replaceWith": "$x"
      }
    ])
    

    Try it on mongoplayground.net.