I have some data that needs to be flattened, which means go from this format:
"user": {
"id": "AEC77ACD-02D3-0057-842F-DC23D6312389",
"name": "Eliza Chukiua",
"email": "eliza.chukiua@booking.com",
"group": "SSO",
"externalId": "eliza.chukiua@booking.com"
To this format:
"user_email": "eliza.chukiua@booking.com",
"user_externalId": "eliza.chukiua@booking.com",
"user_group": "SSO",
"user_id": "AEC77ACD-02D3-0057-842F-DC23D6312389",
"user_name": "Eliza Chukiua"
To do this, the code is
db.collection.update({},
[
{
$set: {
user_id: "$user.id",
user_email: "$user.email",
user_name: "$user.name",
user_externalId: "$user.externalId",
user_group: "$user.group"
}
},
{
$unset: "user"
}
],
{
multi: true
})
The problem is that I have more fields I have to flatten and they not always are on the data set, which means I need a way to flatten all the crap fields, even if I don't know their names. That is because new crappy fields can be created and I have no way to know every single crap field name.
What I am using to test it is this mongodb playground https://mongoplayground.net/p/KXJWzKIUDob, feel free to play around.
How do I flatten every crappy field automatically, without having to $set every single one of them?