Home > Software engineering >  Remove all inner array elements where some fields match conditions on MongoDB?
Remove all inner array elements where some fields match conditions on MongoDB?

Time:10-22

In my MongoDB database I've a collection named "customerProducts" in which I store all customer product data. A document of my collection has the following form:

{
    "customerId" : "12345678",
    "products": [
        {
            "name": "nameOne",
            "type": "DT"    
        },
        {
            "name": "nameTwo",
            "type": "DT"    
        },
        ...
    ]

}

And now I need to remove some products by name and type and I wrote the following script:


db.getCollection('customerProducts').updateMany({
    "customerId": "12345678"
}, {
    $pull: {
        "products.$[product]"
    }
}, {
    arrayFilters: [
        { $and: [{"product.name": {$eq: "nameOne"}}, {"product.type": {$eq: "DT"}}] }
    ]
})

But it doesn't work: can anyone figure out what's wrong?

CodePudding user response:

You don't need to use array filters, you can simply do this:

db.collection.update({
  "customerId": "12345678"
},
{
  $pull: {
    products: {
      name: "nameOne",
      type: "DT"
    }
  }
})

Playground link.

  • Related