Convert Array to Object in JSON DB

Hello : )

Doc was

And became

Its replaces the t,e fields converting the arrays to objects.
It is $addFields all other fields remains the same.
You can run that pipeline below,in any driver.
Its the same code 2x it can wrapped in a function also,to reduce query size.

{
  "aggregate": "testcoll",
  "pipeline": [
    {
      "$addFields": {
        "t": {
          "$arrayToObject": {
            "$zip": {
              "inputs": [
                {
                  "$map": {
                    "input": {
                      "$range": [
                        1,
                        {
                          "$add": [
                            {
                              "$size": "$t"
                            },
                            1
                          ]
                        }
                      ]
                    },
                    "as": "n",
                    "in": {
                      "$concat": [
                        "phone",
                        {
                          "$toString": "$$n"
                        }
                      ]
                    }
                  }
                },
                {
                  "$map": {
                    "input": "$t",
                    "as": "m",
                    "in": {
                      "$trim": {
                        "input": "$$m"
                      }
                    }
                  }
                }
              ]
            }
          }
        }
      }
    },
    {
      "$addFields": {
        "e": {
          "$arrayToObject": {
            "$zip": {
              "inputs": [
                {
                  "$map": {
                    "input": {
                      "$range": [
                        1,
                        {
                          "$add": [
                            {
                              "$size": "$e"
                            },
                            1
                          ]
                        }
                      ]
                    },
                    "as": "n",
                    "in": {
                      "$concat": [
                        "email",
                        {
                          "$toString": "$$n"
                        }
                      ]
                    }
                  }
                },
                {
                  "$map": {
                    "input": "$e",
                    "as": "m",
                    "in": {
                      "$trim": {
                        "input": "$$m"
                      }
                    }
                  }
                }
              ]
            }
          }
        }
      }
    },
    {
      "$out": {
        "db": "testdb",
        "coll": "testcoll1"
      }
    }
  ],
  "cursor": {},
  "maxTimeMS": 1200000
}
1 Like