如何使用MongoDB(不在数组内)删除对象内的对象

时间:2013-12-16 22:31:27

标签: node.js mongodb

假设我有这种结构:

{
    "_id" : ObjectId("52af7c1497bcaf410e000002"),
    "created_at" : ISODate("2013-12-16T22:17:56.219Z"),
    "name" : "Hot",
    "subcategories" : {
        "Loco" : {
            "subcategory" : "Loco",
                "id" : "522423de-fffe-44be-ed3b-93fdd50fdb4f",
                "products" : [ ]
        },
        "Loco2" : {
            "subcategory" : "Loco2",
                "id" : "522423de-fffe-44be-ed3b-93fdd50fd55",
                "products" : [ ]
        },
    }
}

如何从子类别中删除Loco2,使其他所有内容保持不变?

请注意,我的对象选择器是ObjectId,因为其他文档的结构可能与属于不同文档的子类别名称相同。例如,我还可以有另一个这样的对象:

{
    "_id" : ObjectId("52af7c1497bcaf410e000003"),
    "created_at" : ISODate("2013-12-16T22:17:56.219Z"),
    "name" : "Medium",
    "subcategories" : {
        "Loco" : {
            "subcategory" : "Loco",
                "id" : "522423de-fffe-44be-ed3b-93fdd50332b4f",
                "products" : [ ]
        },
        "Loco2" : {
            "subcategory" : "Loco2",
                "id" : "522423de-fffe-44be-ed3b-93fdd522d55",
                "products" : [ ]
        },
    }
}

所以我的查询应该是这样的:db.categories.update({"_id": "ObjectId("52af7c1497bcaf410e000003")"}, {don't know this part yet})

编辑:当我知道要删除的子类别的名称时,答案确实对shell有效,但是我无法在我的Node应用程序中使用它:

    Categories.prototype.delSubcategory = function(categoryId, subcategory, callback) {

    this.getCollection(function(error, category_collection) {

        if(error) callback(error);

        else {

            category_collection.update(

                {_id: category_collection.db.bson_deserializer.ObjectID.createFromHexString(categoryId)},
                { $unset : { "subcategories.Loco2: "" } },
                function(error, subcategory) {

                    if(error) callback(error);

                    else callback(null, subcategory)

                }

            )

        }

    });

};

1 个答案:

答案 0 :(得分:6)

您可以使用$unset operator删除文档或其子对象中的字段。

db.collection_name.update(
      {"_id": ObjectId("52af7c1497bcaf410e000003")}, 
      { $unset : { "subcategories.Loco2" : "" } }
);
相关问题