0

I have a document that looks like the following

{
  "list" :{
    "friends": [
        {
        "Name": "John",
        "Contact": "xyz",
        "Code": "B"
        },
        {
        "Name": "Smith",
        "Contact": "abc",
        "Code": "A"
        }
      ]
   }
}

I'm trying to delete a field using the $unset operator based on a filter. My code looks like:

result = db.collection.update_many({"list.friends.code": "A"}, 
         {"$unset": {"list.friends.$.Name": "", "list.frieds.$.Contact": ""}})

However, I get pymongo.errors.WriteError: Invalid BSON field name 'list.friends.$.Name'

Sivaprasanna Sethuraman
  • 4,014
  • 5
  • 31
  • 60
  • Kindly note that you've "code" using lowercase characters only in your query which does not match the "Code" in your example data... Also, "frieds" should probably be "friends"... – dnickless Feb 15 '18 at 11:04
  • Also, which MongoDB version are you using? – dnickless Feb 15 '18 at 11:06

1 Answers1

1

Try this instead:

result = db.collection.update_many({"list.friends": { $elemMatch: { "Code":"A"}}}, 
     {"$unset": {"list.friends.$.Name": "", "list.friends.$.Contact": ""}})
dnickless
  • 10,733
  • 1
  • 19
  • 34