Mongodb: 从文档中取消设置字段?

Mongodb: Unset Field from Document?

{
 "_id" : ObjectId("55d6cb28725f3019a5241781"),
    {
        "description" : "details of student",
        "displayGroup" : "",
        "role" : [
            {
                "name" : "admin",
                "edit" : "no"
            }
        ],
        "timestamp" : "2015-09-01 15:29:09"
    },
"subject" : {
        "class" : "Fifth",
        "description" : "5th class",
        "displayGroup" : "section A",
        "timestamp" : "2015-09-01 15:29:09"
    }
    }

我有这些数据,我想从我的文档中删除 Subjet Array,其中 Class =5我如何删除?

i 运行 下面这个查询:-

db.collectionName.update({"subject.class":"Fifth"},{$unset:{subject:""}})

但这是给1个匹配没有修改。 我想一次性从我的文档中删除这个 shot.Help 我出去?

假设您有以下文档(必须添加 person 属性,因为它无效)。

> db.coll.findOne({"subject.class": "Fifth"})
{
    "_id" : ObjectId("55d6cb28725f3019a5241781"),
    "person" : {
        "description" : "details of student",
        "displayGroup" : "",
        "role" : [
            {
                "name" : "admin",
                "edit" : "no"
            }
        ],
        "timestamp" : "2015-09-01 15:29:09"
    },
    "subject" : {
        "class" : "Fifth",
        "description" : "5th class",
        "displayGroup" : "section A",
        "timestamp" : "2015-09-01 15:29:09"
    }
}

当您使用 $unset on subject the document is matched and modified. Using update's multi option 时,您可以指示 mongo 更新所有匹配查询的文档。

> db.coll.update({"subject.class": "Fifth"}, {$unset: {subject: ""}}, {multi: true})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

鉴于 subject 已删除,无法再查询 subject.class

通过_id查询可以看到该字段已从文档中删除。

> db.coll.findOne({_id: ObjectId("55d6cb28725f3019a5241781")})
{
    "_id" : ObjectId("55d6cb28725f3019a5241781"),
    "person" : {
        "description" : "details of student",
        "displayGroup" : "",
        "role" : [
            {
                "name" : "admin",
                "edit" : "no"
            }
        ],
        "timestamp" : "2015-09-01 15:29:09"
    }
}