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
Became
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