Home > Enterprise >  Parsing a difficult MongoDB field (with multi-level array)
Parsing a difficult MongoDB field (with multi-level array)

Time:11-17

Hello Experts,

I am trying to parse a MongoDB collection row, and after using $unwind, one of the remaining fields looks like that:

[
    {
        "account_id": "1234",
        "cities": {
            "cityname1": {
                "param1": 1,
                "param2": 2
            }
        }
    },
    {
        "account_id": "2345",
        "cities": {
            "cityname2": {
                "param1": 3,
                "param2": 3
            }
        }
    },
    {
        "account_id": "3456",
        "cities": {
            "cityname3": {
                "param1": 8,
                "param2": 6
            }
        }
    }
]

Now, I would like to continue parsing this field, so I can extract the fieldname/value for account_id, for param1 and for param2, hoping then to sum up the param1 and param2 values. However, when I try to use a second $unwind, I receive those fields with "null" value.

How should I parse this field correctly?

CodePudding user response:

  • $set change cities into array by using $objectToArray
  • $unwind unwind cities array
  • $group group by account_id and cityname then sum up param1 and param2 (you can only group by account_id or cityname, just remove one of them)

aggregate

db.collection.aggregate([
  {
    "$set": {
      cities: {
        "$objectToArray": "$cities"
      }
    }
  },
  {
    "$unwind": "$cities"
  },
  {
    "$group": {
      "_id": {
        account_id: "$account_id",
        "cityname": "$cities.k"
      },
      "sumOfParam1": {
        "$sum": "$cities.v.param1"
      },
      "sumOfParam2": {
        "$sum": "$cities.v.param2"
      }
    }
  }
])

mongoplayground

  • Related