Home > Net >  how to monogo aggregate and make certain changes to its output
how to monogo aggregate and make certain changes to its output

Time:02-03

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?

CodePudding user response:

I try to get correct answer by this query

game_collection.aggregate([
            {
                "$match": {
                    "_id": ObjectId(data["gameId"])
                }
            },
            {
                "$project": {
                    "x": {"$objectToArray": "$markets"},

                }
            },
            {
                "$replaceRoot": {
                    "newRoot": {
                        "gameId": data["gameId"],
                        # "name": "$x.k",
                        "address": "$x.v"
                    }
                }
            },
            {
               "$addFields": {
               "gameId": f"$$this.v.gameId",
                }
            }
         ])

CodePudding user response:

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.

  •  Tags:  
  • Related