user3305063
user3305063

Reputation: 471

deleting an entry from an array in mongo collection

We have a very complex collection structure. I want to delete an entry from it. I am new to mongodb.

The sample collection is as follows,

{
  "rootid": "1",
  "projects": [
    {
      "projectId": "2",
      "proxies": [
        {
          "proxyId": "4",
          "config": {
            "pipeline": [
              {
                "pipelineId": "12",
                "desc": "pipeline"
              },
              {
                "pipelineId": "14",
                "desc": "pipeline1234"
              }
            ]
          }
        }
      ]
    }
  ]
}   

I want to delete an entry from pipeline embedded collection, if it matches the criteria.

Example: if "rootid": "1" ,"projectId": "2", "proxyId": "4", "pipelineId": "12" then I want to delete first entry from pipeline array.

We are using spring boot as a framework. If some one helps with mongo query I will try to convert it with spring mongoTemplate.

Thanks in advance,

Upvotes: 3

Views: 61

Answers (1)

Tom Slabbaert
Tom Slabbaert

Reputation: 22296

Sounds like you want to use arrayFilters combined with $pull to achieve this.

db.collection.update({
  "rootid": "1"
},
{
  "$pull": {
    "projects.$[project].proxies.$[proxy].config.pipeline": {
      pipelineId: "12"
    }
  }
},
{
  arrayFilters: [
    {
      "project.projectId": "2"
    },
    {
      "proxy.proxyId": "4"
    }
  ]
})

Mongo Playground

Upvotes: 4

Related Questions