skip to Main Content
"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" }
    }
])

2

Answers


  1. add UOM to all eliment in Inventory

    db.collection.update( 
       {},
       { $set: { 'ParentType.Inventory.$[].UOM':''} }
    )
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search