user13140381
user13140381

Reputation:

Remove a specific field in mongoDB

My data looks like:

PHARMACY { 
    Name: "Walter", 
    City: "London" 
    UserQuestion: [
       { 
          text: "BlaBlaBla",
          type: "Prescription" 
       }, 
       { 
          text: "BlaBlaBla",
          type: "Medicine request"
       }, 
       { 
          text: "BlaBlaBla",
          type: "Prescription"
       } 
    ]
}

I have to remove from the Pharmacy Walter only the Questions regarding the "Prescription type" between the several questions, so i have to logically remove UserQuestion[0] and UserQuestion[2] . I tried this code

db.pharmacy.update({Name:"Walter"}, {$unset: {type:"Prescription"}} , {multi: true});

but doesn't work, so I tried with the remove method

db.pharmacy.remove({$and: [{Name:"Walter"}, {"UserQuestion.type":"Prescription} ] } );

I hope my problem is clear, Thanks you.

Upvotes: 0

Views: 73

Answers (2)

J.F.
J.F.

Reputation: 15235

You need arrayFilters

Try this query:

db.collection.update({
  "Name": "Walter"
},
{
  "$unset": {
    "UserQuestions.$[af].type": ""
  }
},
{
  "arrayFilters": [
    {
      "af.type": "Prescription"
    }
  ],
  "multi": true
})

This query first find the element that match the name. After that, delete the field type using $unset for every element that match the arrayFilter. And this filter is set just below. We eant those element that .type is Prescription.

Example here

Edit to explain why $operator doesn't works:

Note that using position operator $ the query will not work because, as is explained in the documentation this operator return only the first element that matches the query. And you want to update every element into array that matches, not only the first.

Example that doesn't work here Note how only one object remove the field type.

Upvotes: 1

Sheeri
Sheeri

Reputation: 618

What is the output you got with

db.pharmacy.update({Name:"Walter"}, {$unset: {type:"Prescription"}} , {multi: true});

Were there any matches? My guess is there were matches but no updates.

Try this?

db.pharmacy.update({"Name":"Walter"}, {$unset: {"UserQuestion.type":"Prescription"}} , {multi: true});

db.pharmacy.find({"UserQuestion.type":"Prescription"},{Name":1});

Upvotes: 1

Related Questions