javascriptmongodbmongodb-queryunset

MongoDB unset removes everything in child


I have a db structure like this:

   { "_id" : ObjectId("5fd48e12e5e0fd174c1a7260"), 
     "races" : { 
               "example1" : { "date" : "12/18/2020", "status" : "pending" }, 
               "example2" : { "date" : "12/18/2020", "status" : "domestic" } 
           } 

and I am attempting to just remove example 1 by using the following block of code(javascript):

  self.db  =  client.db("authinfo");
  self.collection = self.db.collection("users");

this.delete_both_races = function (user1) {

    self.collection.updateOne({user:user1} ,{$unset:{races:"example1"}} ,function(error,result){});

same thing happens when running the following command in the mongo.exe command line program:

db.users.updateOne({user:"anything"} , {$unset:{races:"example1"}})

I get the result of(remaining elements after unsetting) :

{ "_id" : ObjectId("5fd48e12e5e0fd174c1a7260") }

desired result :

  { "_id" : ObjectId("5fd48e12e5e0fd174c1a7260"), 
    "races" : { 
                   "example2" : { "date" : "12/18/2020", "status" : "domestic" } 
               } 

Solution

  • You should unset races.example1 instead of races.

    From MongoDB document,

    The specified value in the $unset expression (i.e. "") does not impact the operation.

    To specify a in an embedded document or in an array, use dot notation.

    db.collection.update({},
    {
      $unset: {
        "races.example1": ""
      }
    })
    

    Mongo Playground