Want to change the document structure

Hi I like to change the document structure of {
“_id”:“60546e16000cc037474fad2f”,
“firstVisitDate”:“2021-03-19T09:25:42.892Z”,
“lastVisitDate”:“2021-03-19T12:57:58.885Z”,
“platform”:“gooogle”,
“visits”:5

}
change to
{
“_id”:“60546e16000cc037474fad2f”,
“platform”: {“gooogle”, {
“visits”:5,
“firstVisitDate”:“2021-03-19T09:25:42.892Z”,
“lastVisitDate”:“2021-03-19T12:57:58.885Z”,
}}
}

Please help me on this. I have try the multiple option but not archive this.

Hello and welcome : )

In general its easy to contruct new documents,based on old ones,using field references.
If the document we want to make has few keys we can use literals like
(if it has many we can use $mergeObjects)

{
  "newfield1" "$oldDocField1"
  "newfield2" "$oldDocField2"
  {
    "newfield3" "$oldDocField3"
  }
}

But this is easy to make if we never use a value of the old document,as key to the new document.

The document that you want to convert does that only with 1 key.
“gooogle” value,you want it to become key in new document.

MongoDB doesn’t allow as to use a field reference in the key position

{"$platform" avalue}  

To make those happen,we use $arrayToObject operator.

{"$arrayToObject" [["$platform" avalue]]}  //this works,we are allowed to use reference inside one array

Actually it doesn’t work to make it work you need

let v1=[["$platform" avalue]]
{"$arrayToObject" v1}

The bellow code uses document literals {},and only 1 time the more complicated $arrayToObject.
I send you the command take the “u” part,its a pipeline update,and use it with your driver.

{
  "update": "testcoll",
  "updates": [
    {
      "q": {},
      "u": [
        {
          "$replaceRoot": {
            "newRoot": {
              "$let": {
                "vars": {
                  "doc2_array": [
                    [
                      "$platform",
                      {
                        "visits": "$visits",
                        "firstVisitDate": "$firstVisitDate",
                        "lastVisitDate": "$lastVisitDate"
                      }
                    ]
                  ]
                },
                "in": {
                  "$let": {
                    "vars": {
                      "doc2": {
                        "$arrayToObject": "$$doc2_array"
                      }
                    },
                    "in": {
                      "_id": "$_id",
                      "platform": "$$doc2"
                    }
                  }
                }
              }
            }
          }
        }
      ],
      "multi": true
    }
  ]
}

I tested it i think it does what you need to do

Screenshot from 2021-07-03 04-17-52
Became
Screenshot from 2021-07-03 04-17-16

In general dont hold data in key places,keys are for fields that describe the data.
Keep the data in value places or inside arrays, i think it works much easier with mongodb