ivanof81
ivanof81

Reputation: 167

Rename a field from an array for all documents of collection - MongoDB

I have a document like the following

[
  {
    "_id" : NUUID("51611712-b966-4562-8937-06015a6691ec"),
    "Name":"Alex",
    "Descriptions" : [ 
        {
            "Name" : "Descr1",
            "Items" : [ 
                {
                    "ItemsType" : {
                        "_id" : 1,
                        "Name" : ""
                    },
                    "Field1" : 1,
                    "Field2" : null
                }, 
                {
                    "ItemsType" : {
                        "_id" : 2,
                        "Name" : ""
                    },
                    "Field1" : 1,
                    "Field2" : null
                }, 
                {
                    "ItemsType" : {
                        "_id" : 3,
                        "Name" : ""
                    },
                    "Field1" : 1,
                    "Field2" : null
                }
            ]
        }
    ],
    "DateCreated" : ISODate("2019-07-29T11:33:19.090Z"),
    "DateModified" : ISODate("2019-12-23T08:08:40.339Z"),
    "IsDeleted" : false,
    "LegalEntityIdentifier" : "",
  }, 
  ...
]

How rename array fields with path "Descriptions.Items.ItemType" to new name "Descriptions.Items.Type" for all documents of the collection?

Upvotes: 0

Views: 49

Answers (1)

Valijon
Valijon

Reputation: 13103

You need to use $map operator

db.collection.aggregate([
  {
    $addFields: {
      Descriptions: {
        $map: {
          input: "$Descriptions",
          as: "desc",
          in: {
            $map: {
              input: "$$desc.Items",
              as: "item",
              in: {
                Field1: "$$item.Field1",
                Field2: "$$item.Field2",
                Type: "$$item.ItemsType"
              }
            }
          }
        }
      }
    }
  }
])

MongoPlayground

Upvotes: 3

Related Questions