【问题标题】:How to remove a field having a specified value from a MongoDB document?如何从 MongoDB 文档中删除具有指定值的字段?
【发布时间】:2021-01-21 06:54:50
【问题描述】:

这是 mongo db 中的给定文档,如下所示

{

"emailid": "xxx.gmail",

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

}

在这里我想删除设备内部的字段,即 "created_time": '', "token": '1345' 这里的token值是已知的,所以需要删除“created_time”以及输出的“token”

{

"emailid": "xxx.gmail",

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

}

我尝试了如下未设置的代码

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

and used 

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

但它不起作用。谁能告诉如何删除这个指定的字段。提前致谢。

【问题讨论】:

标签: database mongodb mongodb-query


【解决方案1】:

由于要移除的对象在数组中,所以必须这样使用$pull

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

在此查询中,您告诉 mongo:“从数组 devices 中删除 -using $pull- 一个字段,其中 token123”。

例如here

编辑:

此外,如果您只想将一个字段删除到数组中的 objec 而不是对象本身,您可以使用$[<identifier>] 进行过滤,然后使用$unset 像这样:

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

在此查询中,使用arrayFilters 只能在token123 的对象中使用$unset。你也可以使用created_time进行过滤。

例如here

【讨论】:

    猜你喜欢
    • 2021-04-14
    • 1970-01-01
    • 2020-11-21
    • 2011-10-14
    相关资源
    最近更新 更多