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

时间:2016-11-24 10:40:13

标签: mongodb unset

{
 "_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数组,其中Class = 5我可以删除吗?

我运行以下查询: -

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

但是这给了1场比赛没有修改。 我想一次性从我的文档中删除它。帮助我吗?

1 个答案:

答案 0 :(得分:1)

假设您有以下文档(必须添加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"
    }
}

subject上使用$unset时,会对文档进行匹配和修改。使用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"
    }
}