Search This Blog

Wednesday, March 21, 2018

working with nexted array in mongo


We will create a sample collection in mongo

    db.nx.insert(
    {
    "user":"john",
    "cart_item":[
            {
             "product":"product1",
             "unit_price":5,
             "qty":2,
             "total":0
            },
            {
             "product":"product2",
             "unit_price":6,
             "qty":3,
             "total":0
            },
            {
             "product":"product3",
             "unit_price":4,
             "qty":6,
             "total":0
            }
        ]
    }
    )

lets see inserted document

    db.nx.find().pretty()

    output:
        {
            "_id" : ObjectId("5ab290094d5d23c1ed27c8a2"),
            "user" : "john",
            "cart_item" : [
                {
                    "product" : "product1",
                    "unit_price" : 5,
                    "qty" : 2,
                    "total" : 0
                },
                {
                    "product" : "product2",
                    "unit_price" : 6,
                    "qty" : 3,
                    "total" : 0
                },
                {
                    "product" : "product3",
                    "unit_price" : 4,
                    "qty" : 6,
                    "total" : 0
                }
            ]
        }


We want to update cart_item object array total using unit_price & qty.

Here is one way to do so


db.nx.find({ "_id" : ObjectId("5ab290094d5d23c1ed27c8a2")}).forEach(function(item) { 
  var new_cart_item=[];
  for(var i=0;i < item.cart_item.length;i++){
     item.cart_item[i].total = item.cart_item[i].unit_price * item.cart_item[i].qty;
     new_cart_item.push(item.cart_item[i])
  }

  db.nx.update({ "_id" : ObjectId("5ab290094d5d23c1ed27c8a2")}, {
    $set: { "cart_item": new_cart_item }
  })
})

now we will see modified collection

db.nx.find().pretty()
output:
{
    "_id" : ObjectId("5ab290094d5d23c1ed27c8a2"),
    "user" : "john",
    "cart_item" : [
        {
            "product" : "product1",
            "unit_price" : 5,
            "qty" : 2,
            "total" : 10
        },
        {
            "product" : "product2",
            "unit_price" : 6,
            "qty" : 3,
            "total" : 18
        },
        {
            "product" : "product3",
            "unit_price" : 4,
            "qty" : 6,
            "total" : 24
        }
    ]
}

No comments:

Post a Comment