【问题标题】:Mongodb $unset leaves empty array object(javascript)Mongodb $unset 留下空数组对象(javascript)
【发布时间】:2014-06-20 18:18:40
【问题描述】:

我正在使用 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 的页面,但这不适合这里。

谢谢!

【问题讨论】:

    标签: javascript node.js mongodb unset


    【解决方案1】:

    如果您真的想先unset,然后将缺少key 的元素从数组中拉出,请使用:

    db.test.update(
      { "_id": 1 },  // you can also use { } to clean up the whole collection
      { $pull: { "list": { "key": {$exists: false} } } }
    )
    

    但如果没有充分的理由这样做,请使用pull 一次性完成:

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

    您可以使用 pull 从文档中删除其中list 包含key 的值为b:

    db.test.update({ 
      "list.key": "b" }, 
      { $pull: { "list": {"key": "b" } } 
    })
    

    这会从数组中删除相应的元素:

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

    【讨论】:

    • 非常感谢!两种方法都对我有用,我更喜欢直接 $pull 进行一项较小的操作。
    猜你喜欢
    • 1970-01-01
    • 2019-02-13
    • 1970-01-01
    • 2016-06-10
    • 2019-03-14
    • 2020-02-09
    • 2011-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多