springmongodb

MongoDB Rename field with derived Value of another field


I have a collection like -

[  {
    'k': 'Troubleshooting',
    'hour': '2024-10-10T16',
    'v': [ 'WebPage, Login' ]
  },
  {
    'k': 'TroubleshootingMe',
    'hour': '2024-10-07T01',
    'v': [ 'Accounts, etc' ]
  }
]

I wish to aggregate pipeline that results me documents like below -

[  {
    'hour': '2024-10-10T16',
    'Troubleshooting': [ 'WebPage, Login' ]
  },
  {
    'hour': '2024-10-07T01',
    'TroubleshootingMe': [ 'Accounts, etc' ]
  }
]

I know that I can use replaceroot Like below -

{
    $replaceRoot: {
      newRoot: {
        $arrayToObject: [
          [
            {
              k: "$k",
              v: "$v"
            }
          ]
        ]
      }
    }
  }

But, that can be done only when I have 2 fields k & v. Is there a way I can select third hour field as well ...?


Solution

  • I think you're looking for the $mergeObjects operator. You can see a general reference for using that operator in conjunction with $replaceRoot/$replaceWith here in the documentation.

    In your situation the pipeline would look something like:

    db.collection.aggregate([
      {
        $replaceWith: {
          $mergeObjects: [
            {
              hour: "$hour"
            },
            {
              "$arrayToObject": [
                [
                  {
                    k: "$k",
                    v: "$v"
                  }
                ]
              ]
            }
          ]
        }
      }
    ])
    

    Mongoplayground here. Output:

    [
      {
        "Troubleshooting": [
          "WebPage, Login"
        ],
        "hour": "2024-10-10T16"
      },
      {
        "TroubleshootingMe": [
          "Accounts, etc"
        ],
        "hour": "2024-10-07T01"
      }
    ]