Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/428.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mongodb$unset保留空数组对象(javascript)_Javascript_Node.js_Mongodb_Unset - Fatal编程技术网

Mongodb$unset保留空数组对象(javascript)

Mongodb$unset保留空数组对象(javascript),javascript,node.js,mongodb,unset,Javascript,Node.js,Mongodb,Unset,我正在使用mongo“$unset”命令删除索引未知的特定条件下的所有匹配文档 假设集合看起来像:- { "_id" : 1, "list" : [ { "key" : "a" }, { "key" : "b" }, { "key" : "c" } ] } Mongo shell命令,用于取消设置与“b”

我正在使用mongo“
$unset
”命令删除索引未知的特定条件下的所有匹配文档

假设集合看起来像:-

{
    "_id" : 1,
    "list" : [
        {
            "key" : "a"
        },
        {
            "key" : "b"
        },
        {
            "key" : "c"
        }
    ]
}
Mongo shell命令,用于取消设置与
“b”匹配的密钥:-

db.test.update({"list.key":"b"}, {$unset: {'list.$.key':"b"}})
结果:-

{
    "_id" : 1,
    "list" : [ {"key" : "a"}, {}, {"key" : "c"} ]
}
回答:-如何删除空数组对象

注意:-我读过一些页面建议使用
$pull:null
,但这不适合这里

谢谢

如果您确实想
先取消设置
,然后将缺少的元素
从阵列中拉出,请使用:

db.test.update(
  { "_id": 1 },  // you can also use { } to clean up the whole collection
  { $pull: { "list": { "key": {$exists: false} } } }
)
但是,如果没有充分的理由使用
一次性完成:

db.test.insert({ 
  "_id" : 1, 
  "list" : [ { "key": "a" }, { "key": "b" }, { "key": "c" } ] 
})
您可以使用pull从文档中删除
列表
包含值为
b的

db.test.update({ 
  "list.key": "b" }, 
  { $pull: { "list": {"key": "b" } } 
})
这将从阵列中删除相应的元素:

db.test.find()
{ "_id" : 1, "list" : [ { "key" : "a" }, { "key" : "c" } ] }

谢谢!这两种方法对我都有效,我更喜欢直接$pull进行一次较小的操作。