Let's say I've got this structure:
{
"_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" : [ ]
},
}
}
How can I remove Loco2 from within subcategories leaving everything else intact?
Please note that my object selector got be the ObjectId as there will be other documents that have the structure with possibly the same subcategories name that belongs to different documents. For instance, I could also have another object like this:
{
"_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" : [ ]
},
}
}
So my query should be along those lines: db.categories.update({"_id": "ObjectId("52af7c1497bcaf410e000003")"}, {don't know this part yet})
EDIT: The answer did work on the shell when I know the name of the subcategory I want to delete, however I couldn't get it to work within my Node app:
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)
}
)
}
});
};