Skip to main content



Spring MongoDB Rename field with derived Value of another field


Input Collection - 

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

]


Expected Output - 

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

] 


Above Can be achieved by $replaceRoot/$replaceWith as follows -

{
    $replaceWith: {
      $mergeObjects: [
        {
          hour: "$hour"
        },
        {
          "$arrayToObject": [
            [
              {
                k: "$k",
                v: "$v"
              }
            ]
          ]
        }
      ]
    }
  }
or
{
    $replaceRoot: {
	 newRoot: {
      $mergeObjects: [
        {
          hour: "$hour"
		 
        },{
		 day: "$day"
		},{
		  week: "$week"
		},
        {
          "$arrayToObject": [
            [
              {
                k: "$k",
                v: "$v"
              }
            ]
          ]
        }
      ]
	  }
    }
  }

Spring code for same is as below - 
import org.bson.Document;
import org.springframework.data.mongodb.core.aggregation.ReplaceRootOperation;

String replaceWithStr = "{ $mergeObjects: [ { hour : \"$hour\" } , { date : \"$date\" } , { week : \"$week\" } , { \"$arrayToObject\": [ [ { k: \"$key\", v: \"$value\" } ] ] } ] } ";

ReplaceRootOperation replaceRootOperation = ReplaceRootOperation.builder()

.withDocument(Document.parse(replaceWithStr));

Comments