MongoDb

How to rename an array field in MongoDB?

Below are the MongoDB sample recipes, which will be useful to rename the fields in MongoDB.

db.sample.insert(
 {
    "_id" : ObjectId("626160c65c9ca2b5d77e3008"),
    "Mobile" : {
        "Brands" : [ 
            {
                "Model" : {
                    "modelname" : "X Phone",
                    "year" : "2021"
                }
            }, 
            {
                "Model" : {
                    "modelname" : "A Phone",
                    "year" : "2022"
                }
            }
        ]
    }
})

Let’s see an example of renaming the array field modelname to the name

db.getCollection("sample").updateMany({}, [
  {
    $set: {
      "Mobile.Brands": {
        $map: {
          input: "$Mobile.Brands",
          in: {
            Model: {
              $mergeObjects: [
                "$$this.Model",
                { name: "$$this.Model.modelname" },
              ],
            },
          },
        },
      },
    },
  },
  { $unset: "Mobile.Brands.Model.modelname" },
])
db.sample.find().forEach(function (e) {
  var t = e.Mobile.Brands;
  t.forEach(function (e) {
    e.Model.name = e.Model.modelname;
    delete e.Model.modelname;
  });

  db.sample.update(
    {
      _id: e._id,
    },
    {
      $set: {
        "Mobile.Brands": t,
      },
    }
  );
});

Hope this mongob solution will help you to rename the fields in array structure.