Let's say I have 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 subcategories, leaving everything else intact?
Please note that my object selector was ObjectId, as there will be other documents that have a structure, possibly with the same subcategory name, which refers to different documents. For example, I could have another object:
{
"_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 these lines: db.categories.update({"_id": "ObjectId("52af7c1497bcaf410e000003")"}, {don't know this part yet})
EDIT: The answer really worked on the shell when I know the name of the subcategory I want to delete, however I could not get it to work in my Node application:
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)
}
)
}
});
};