简体   繁体   中英

How to remove a field having a specified value from a MongoDB document?

Here is a given document in mongo db as below

{

"emailid": "xxx.gmail",

"user_devices": [],
"devices": [{
    "created_time": 1607153351,
    "token": 123
},
{
    "created_time": 1807153371,
    "token": 1345
}]

}

Here i want to remove the field inside devices ie "created_time": '', "token": '1345' here token value is known, so need to delete "created_time" along with "token" where output is like

{

"emailid": "xxx.gmail",

"user_devices": [],
"devices": [{
    "created_time": 1607153351,
    "token": 123
}]

}

I tried unset code like below

var myquery = { 'emailid': emailid , 'devices.token':1345};
        var newvalues = { $unset:{
        'devices.created_time':'',
        'devices.token':1345
        } };

and used 

updateOne(myquery, newvalues, function(err, res))

but it does not work. Can anyone tell how to remove this specified field. Thanks in advance.

Since the object you want to remove is in an array, you have to use$pull in this way:

db.collection.update({
  "emailid": "xxx.gmail"
},
{
  "$pull": {
    "devices": {
      "token": 123
    }
  }
})

In this query you are telling mongo: "Remove -using $pull - one field from the array devices where token is 123 ".

Example here

Edit:

Also, if you want to remove only one field into objec within array and not the object itself, the you can use $[<identifier>] to filter and then $unset like this:

db.collection.update({
  "emailid": "xxx.gmail"
},
{
  "$unset": {
    "devices.$[elem].created_time": ""
  }
},
{
  "arrayFilters": [
    {
      "elem.token": 123
    }
  ]
})

In this query, using arrayFilters you can $unset only in the object where token is 123 . You can use created_time to filter if you want too.

Example here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM