I have a nested documents something as below:
{
"_id" : ObjectId("5ff5f7625aa45b9dd4846794"),
"id" : "4_35763098",
"sync_details" : {
"2058456" : {
"tenant" : {
"id" : "2058456",
"name" : "MWH"
},
"last_updated" : 1626440150,
"test_company" : "19322",
"agreement" : "3",
"sync_status" : true
},
"2058457" : {
"tenant" : {
"id" : "2058457",
"name" : "SFC"
},
"last_updated" : 1626440158,
"test_company" : "19319",
"agreement" : "1",
"sync_status" : true
},
"2058459" : {
"tenant" : {
"id" : "2058459",
"name" : "MCS -EPS"
},
"last_updated" : 1626440165,
"test_company" : "19305",
"agreement" : "8",
"sync_status" : true
}
}
}
Here I need to rename “test_company” key to “comopany” in all the nested dictionary. How to do the smae?
Simon_Bieri
(traceurSaimn)
September 16, 2022, 11:00am
3
In my oppinion such an operation requires a recreation of the collection.
I would run the following aggregation pipeline and insert the results in another collection. You can then replace your old collection with the new one if everything worked as you wanted.
// Requires official MongoShell 3.6+
db = db.getSiblingDB("<yourDB>");
db.getCollection("<yourCollection>").aggregate(
[
{
"$addFields" : {
"sync_details_array" : {
"$objectToArray" : "$sync_details"
}
}
},
{
"$unwind" : {
"path" : "$sync_details_array",
"preserveNullAndEmptyArrays" : true
}
},
{
"$addFields" : {
"sync_details_array.v.comopany" : "$sync_details_array.v.test_company"
}
},
{
"$unset" : [
"sync_details_array.v.test_company"
]
},
{
"$group" : {
"_id" : "$_id",
"id" : {
"$first" : "$_id"
},
"sync_details_array" : {
"$push" : "$sync_details_array"
}
}
},
{
"$addFields" : {
"sync_details" : {
"$arrayToObject" : "$sync_details_array"
}
}
},
{
"$unset" : [
"sync_details_array"
]
}
]
);
Simon_Bieri
(traceurSaimn)
September 16, 2022, 11:09am
4
Here is the .js code to import in your system.
db.getCollection("<yourCollection>").aggregate(
// Pipeline
[
// Stage 1
{
$addFields: {
"sync_details_array": {"$objectToArray": "$sync_details"}
}
},
// Stage 2
{
$unwind: {
path: "$sync_details_array",
preserveNullAndEmptyArrays: true
}
},
// Stage 3
{
$addFields: {
"sync_details_array.v.comopany": "$sync_details_array.v.test_company"
}
},
// Stage 4
{
$unset: ["sync_details_array.v.test_company"]
},
// Stage 5
{
$group: {
_id: "$_id",
id: { "$first" : "$_id" },
sync_details_array: {"$push": "$sync_details_array"}
}
},
// Stage 6
{
$addFields: {
"sync_details": {"$arrayToObject": "$sync_details_array"}
}
},
// Stage 7
{
$unset: ["sync_details_array"]
}
],
// Options
{
}
// Created with Studio 3T, the IDE for MongoDB - https://studio3t.com/
);