MongoDb Array Update Operators

  • 2. $addToSet
  • 3. $pop
  • 4. $pull
  • 5. $pullAll
  • 6a. Positional Operator $
  • 6b. Positional Operator $ in Nested Docs
  • 7.Positional Operator $ with $elemMatch
  • 8. $inc Operator for increment value
  • Add one more Nested Array 1
  • 2. Remove Child Array from Parent Array
  • ArrayFilter


2. $addToSet

$addToSet do not add the item to the given field if it already contains it, on the other hand $push will add the given object to field whether it exists or not.

{_id: "docId", items: [1, 2]}
db.items.update({_id:"docId"}, {$addToSet:{items: 2}}); // This won't update the document as it already contains 2
db.items.update({_id:"docId"}, {$push: {item:2}}); // this will update the document. new document {_id: "docId", items:[1,2,2]}

3. $pop

//Remove "item2 from array"
db.shoppingCart.updateMany(
    {index: 1},     
    { 
        $pop: {
            cart: 1 //["item1", "item2"]
            }
    },
    {}
)

4. $pull

//Add array
db.shoppingCart.update(
    {index: 1},     
    { 
        $addToSet: {
            spentAmount: {$each: [
                NumberInt(400),NumberInt(700),
                NumberInt(800),NumberInt(200),
                NumberInt(500)
                ]}
            }
    },
    {}
)
//Pull operator
db.shoppingCart.update(
    {index: 1},     
    { 
        $pull: {
            spentAmount: {$gt: 500 } //spentAmount:  500
            }
    },
    {}
)

5. $pullAll

db.shoppingCart.update(
    {index: 1},     
    { 
        $pullAll: {
            spentAmount: [400,500]
            }
    },
    {}
)

6. Positional Operator $

//Add array
db.shoppingCart.updateOne(
    {index: 1},     
    { 
        $push: {
            cart:{ $each: ["item1","item2","item3","item4","item5",]}
            }
    },
    {}
)
//Update an item in array
db.shoppingCart.updateOne(
    {index: 1, cart: "item2"},     
    { 
        $set: {
            "cart.$": "updatedItem2"
            }
    },
    {}
)
//Remove Item 
db.shoppingCart.updateOne(
    {index: 1, cart: "item3"},
    { 
        $unset: {
            "cart.$": 1 // ["item1","item2",null,"item4"]
            }
    },
    {}
)

$unset in array will create a null into the array, so we need to pull the element.

db.shoppingCart.updateOne(
    {index: 1},
    { 
        $pull: {
            "cart": null
            }
    },
    {}
)

6. Positional Operator $ in Nested Docs

//Remove element from array using pull $in / $pullAll
db.shoppingCart.updateMany(
    {"index" : 1},
    { 
        $pull: {
                cart: {$in: ["item1","item1", "updatedItem2", "item4", "item5"]}
            }
    },
    {}
)
//Add Array of Object to create nested document
db.shoppingCart.updateMany(
    {},
    { 
        $push: {
                cart: {$each: [{"title":"TV"}, {"title":"Phone"}]}
            }
    },
    {}
)

Adding property into array of object

db.shoppingCart.updateOne(
    {index:1, "cart.title":"TV"},
    { 
        $set: {
                "cart.$.price": NumberInt(322),
                "cart.$.quantity": NumberInt(2)
            }
    },
    {}
)
//OUTPUT : 
/* 1 */
{
    "_id" : ObjectId("5f1117495ad742b2ac38ebf1"),
    "index" : 1,
    "processed" : false,
    "cart" : [ 
        {
            "title" : "TV",
            "price" : 322,
            "quantity" : 2
        }, 
        {
            "title" : "Phone"
        }
    ],
    "updatedAt" : ISODate("2020-07-17T06:28:58.598Z"),
    "spentAmount" : [ 
        200
    ]
}

In the above example we matched only one field (“cart.title”:”TV”). If we want to match nested document by two more field (“cart.title”:”TV”, “cart.price”:”332″) to update quantity, we will use $elemMatch

7.Positional Operator $ with $elemMatch


Here both filed should match to update cart.

db.shoppingCart.updateOne(
    {index:1, 
      cart: {$elemMatch: {
          title: "TV",
          price: 322
          }}
    },
    { 
        $set: {
                "cart.$.quantity": NumberInt(5)
            }
    },
    {}
)
//OUTPUT: 
/* 1 */
{
    "_id" : ObjectId("5f1117495ad742b2ac38ebf1"),
    "index" : 1,
    "processed" : false,
    "updatedAt" : ISODate("2020-07-17T06:28:58.598Z"),
    "spentAmount" : [ 
        200
    ],
    "cart" : [ 
        {
            "title" : "TV",
            "price" : 322,
            "quantity" : 5,
            "ChildCart" : [ 
                {
                    "key1" : "value1"
                }
            ]
        }, 
        {
            "title" : "Phone"
        }
    ]
}

8. $inc Operator for increment value

db.shoppingCart.updateOne(
    {index:1, 
      cart: {$elemMatch: {
          title: "TV",
          price: 322
          }}
    },
    { 
        $inc: {
                "cart.$.quantity": NumberInt(6)
            }
    },
    {}
)
//OUTPUT : 
/* 1 */
{
    "_id" : ObjectId("5f1117495ad742b2ac38ebf1"),
    "index" : 1,
    "processed" : false,
    "updatedAt" : ISODate("2020-07-17T06:28:58.598Z"),
    "spentAmount" : [ 
        200
    ],
    "cart" : [ 
        {
            "title" : "TV",
            "price" : 322,
            "quantity" : 11,
            "ChildCart" : [ 
                {
                    "key1" : "value1"
                }
            ]
        }, 
        {
            "title" : "Phone"
        }
    ]
}

Add one more Nested Array 1


db.shoppingCart.updateOne(
    {index:1, "cart.title":"TV"},
    { 
        $push: {                
                "cart": {ChildCart:[]}
            }
    },
    {}
)
//OUTPUT : 
/* 1 */
{
    "_id" : ObjectId("5f1117495ad742b2ac38ebf1"),
    "index" : 1,
    "processed" : false,
    "cart" : [ 
        {
            "title" : "TV",
            "price" : 322,
            "quantity" : 2
        }, 
        {
            "title" : "Phone"
        }, 
        {
            "ChildCart" : []
        }
    ],
    "updatedAt" : ISODate("2020-07-17T06:28:58.598Z"),
    "spentAmount" : [ 
        200
    ]
}

—–

2. Remove Child Array from Parent Array


{
    "_id" : ObjectId("5f1117495ad742b2ac38ebf1"),
    "index" : 1,
    "processed" : false,
    "cart" : [ 
        {
            "title" : "TV",
            "price" : 322,
            "quantity" : 2,
            "ChildCart" : [ 
                {
                    "key1" : "value1"
                }
            ]
        }, 
        {
            "title" : "Phone"
        }, 
        {
            "ChildCart" : []
        }
    ],
    "updatedAt" : ISODate("2020-07-17T06:28:58.598Z"),
    "spentAmount" : [ 
        200
    ]
}
db.shoppingCart.updateOne(
    {index:1},
    { 
        $pull: {                
                cart:{ChildCart:[]}
            }
    },
    {}
)
//Output : 
/* 1 */
{
    "_id" : ObjectId("5f1117495ad742b2ac38ebf1"),
    "index" : 1,
    "processed" : false,
    "updatedAt" : ISODate("2020-07-17T06:28:58.598Z"),
    "spentAmount" : [ 
        200
    ],
    "cart" : [ 
        {
            "title" : "TV",
            "price" : 322.0,
            "quantity" : 2.0,
            "ChildCart" : [ 
                {
                    "key1" : "value1"
                }
            ]
        }, 
        {
            "title" : "Phone"
        }
    ]
}

Reference

MongoDB Update

Leave a Reply

Your email address will not be published. Required fields are marked *