Home > OS >  how to aggregate data in mongodb for each record
how to aggregate data in mongodb for each record

Time:01-05

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?

CodePudding user response:

  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

  •  Tags:  
  • Related