[Fixed] deleting an object from array in mongo collection

Issue

I have a mongo schema like this.

{
 userID:19202,
 products:[ { id:020, name:'first'  }]
}

I want to pop items from the product array based on id. I used the following command. although it didn’t give any error, it also not deleting elements from an array.

 userCart.updateOne(
                { userID:userID},
                { $pull: { products: { id:id } } }
              )
             .then((data) =>
             {
                 if(data)
                 {

 //data is {
        "n": 1,
        "nModified": 0,
        "ok": 1
    }
                     return res.json({
                         status:true,
                         message:"cart updated"
                     })
                 }
             })

Solution

Demo – https://mongoplayground.net/p/mh6fXN21vyR

Make sure id and products.id are of the same type as in your document in the database. As your sample, both should be numbers.

if they both are number

db.collection.update({
  userID: 19202
},
{
  $pull: {
    "products": { id: 20 }
  }
})

Not Working here – https://mongoplayground.net/p/3zhv8yoH2o9 when "products": { id: "20" }. products.id is a string in the mongo query and in the database in number so mismatched.

Leave a Reply

(*) Required, Your email will not be published