Home > OS >  MongoDB - How to remove elements by certain criteria in array of objects?
MongoDB - How to remove elements by certain criteria in array of objects?

Time:10-15

I have a project where i use mongodb as database. So i would like to the following

For example, there is a collection of products

products: [
  {
    "name": "Product 1",
    "products": [
      {
        "file": "data:image/;base64,",
        "name": "Sacs bordeaux",
        "description": "Pour les crémations Référence",
        "id": 13,
        "path": ""
      },
      {
        "file": "data:image/;base64,",
        "name": "Sacs bordeaux",
        "description": "Pour les crémations Référence",
        "id": 11,
        "path": ""
      },
     {
        "file": "data:image/;base64,",
        "name": "Sacs bordeaux",
        "description": "Pour les crémations Référence",
        "id": 10,
        "path": ""
     }
    ]
  },
  {
    "name": "Product 2",
    "products": [
     {
        "file": "data:image/;base64,",
        "name": "Sacs bordeaux",
        "description": "Pour les crémations Référence",
        "id": 10,
        "path": ""
     },
     {
        "file": "data:image/;base64,",
        "name": "Sacs bordeaux",
        "description": "Pour les crémations Référence",
        "id": 11,
        "path": ""
     }

    ]
  }
]

What I would like is to remove all the objects which have ID: 10 from all the documents of collection products using updatemany or any MongoDB query So after the update, the final doc should be like this

products: [
  {
    "name": "Matériel crémation",
    "products": [
      {
        "file": "data:image/;base64,",
        "name": "Sacs bordeaux",
        "description": "Pour les crémations Référence",
        "id": 13,
        "path": ""
      },
      {
        "file": "data:image/;base64,",
        "name": "Sacs bordeaux",
        "description": "Pour les crémations Référence",
        "id": 11,
        "path": ""
      }
    ]
  },
  {
    "name": "Documents",
    "products": [
     {
        "file": "data:image/;base64,",
        "name": "Sacs bordeaux",
        "description": "Pour les crémations Référence",
        "id": 11,
        "path": ""
     }

    ]
  }
]

CodePudding user response:

Chain up $filter with $set

db.collection.update({},
[
  {
    $set: {
      products: {
        "$filter": {
          "input": "$products",
          "as": "p",
          "cond": {
            $ne: [
              "$$p.id",
              10
            ]
          }
        }
      }
    }
  }
],
{
  multi: true
})

Here is the Mongo Playground for your reference.

  • Related