如何使用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,使所有其他内容完好无损?

请注意,我的对象select器是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) } ) } }); }; 

您可以使用$ unset运算符从文档或其子对象中删除字段。

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