Home > other >  Add new column to multi nested array in mongo db
Add new column to multi nested array in mongo db

Time:06-20

"ParentType": {
    "Food": [
      {
        "Name": "Burger",
        "FoodId": "5e3abe145c1bfb31b4e335de",
        "Price": 0,
        "Quantity": 1,
        "SubCategory": 0
      }
    ],
    "Inventory": [
      {
        "Name": "Small Popcorn",
        "InventoryId": "5e3a64245c1bfb31b4e335b7",
        "Price": 0,
        "Quantity": 1,
        "SubCategory": 0
      }
    ]
  }

I need to add UOM as new column only for Inventory array.I have used aggregate as below but collection is not getting updated.Pls help me with adding this new Column in mongodb

 db.Concession.aggregate([   
    {
      $addFields: { ParentType.Inventory.UOM: "null" }
    }
])

CodePudding user response:

add UOM to all eliment in Inventory

db.collection.update( 
   {},
   { $set: { 'ParentType.Inventory.$[].UOM':''} }
)

CodePudding user response:

Option 1: ( Update/$set 3.6 )

db.collection.update({},
{
 $set: {
   "ParentType.Inventory.$[].UOM": null
 }
},
{
 multi: true
})

Explained:

  1. Use update() operation with positional operator $[] ( mongoDB 3.6 )
  2. Use option multi to update all documents in collection matching the filter criteria

Playground

Option 2: ( Update/aggregation 4.2 )

db.collection.update({},
[
 {
  $addFields: {
  "ParentType.Inventory": {
    "$map": {
      input: "$ParentType.Inventory",
      as: "i",
      in: {
        "$mergeObjects": [
          "$$i",
          {
            UOM: null
          }
        ]
      }
     }
   }
  }
 }
],
{
  multi: true
})

Explained:

  1. Use update with aggregation pipeline ( mongoDB 4.2 )
  2. In aggregation use the addFileds with mergeObjects so you add the new fields to the array element.
  3. Use multi:true to affect all documents in collection matching the filter criteria

Playground 2

  • Related