Search code examples
pythonmongodbdjango-rest-frameworkaggregation-frameworkpymongo

MongoDB - How to aggregate data for each record


I have some stored data like this:

{
    "_id" : 1,
    "serverAddresses" : {
        "name" : "0.0.0.0:8000",
        "name2": "0.0.0.0:8001"
    }
}

I need aggregated data to this:

[
  {
    "gameId": "1",
    "name": "name1",
    "url": "0.0.0.0:8000"
  },
  {
    "gameId": "1",
    "name": "name2",
    "url": "0.0.0.0:8001"
  }
]

What is the solution without using for loop?


Solution

    1. $project - Add addresses field by converting $serverAddress to (key-value) array.
    2. $unwind - Descontruct addresses field to multiple documents.
    3. $replaceRoot - Decorate the output document based on (2).
    db.collection.aggregate([
      {
        "$project": {
          "addresses": {
            "$objectToArray": "$serverAddresses"
          }
        }
      },
      {
        $unwind: "$addresses"
      },
      {
        "$replaceRoot": {
          "newRoot": {
            gameId: "$_id",
            name: "$addresses.k",
            address: "$addresses.v"
          }
        }
      }
    ])
    

    Sample Mongo Playground