How to rename a field name inside nested array?

I wanted to rename field inside a nested array which looks like below:
So I want to rename StockCode field name to ArticleNo in every Items element.

        {
            "_id": "44f9d742-4070-4980-a32b-90e79bedd96a",
            "Configuration": {
              "Orders": [
                {
                  "Items": [
                    {                      
                      "StockCode": "123456",
                      "OrderedQuantity": 1,                     
                    },
                    {                      
                      "StockCode": "789658",
                      "OrderedQuantity": 4                    
                    }
                 ]
              }
           ]
        }
    }

What is the aggregation I could use in this situation, the complete aggregation is also very welcome.

Thank you for your attention.

Hello @Krishna, Welcome to MongoDB community forum,

You can try update with aggregation pipeline starting from MongoDB 4.2,

  • $map to iterate loop of Orders array
  • $map to iterate loop of Items array and rename StockCode property to ArticleNo and return other fields
  • $mergeObjects to merge current object of Orders and update property Items
db.collection.updateMany(
  {},
  [{
    $set: {
      "Configuration.Orders": {
        $map: {
          input: "$Configuration.Orders",
          in: {
            $mergeObjects: [
              "$$this",
              {
                Items: {
                  $map: {
                    input: "$$this.Items",
                    in: {
                      ArticleNo: "$$this.StockCode",
                      OrderedQuantity: "$$this.OrderedQuantity"
                    }
                  }
                }
              }
            ]
          }
        }
      }
    }
  }]
)

@turivishal Thank you, worked like a charm

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.