如何使用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" : "" } } );
- mongoose保存请求正文中的所有参数
- MongoDB返回所有文件的字段没有重复?
- Mongodb来自多个进程的查询; 如何实现primefaces性?
- 存储在MongoDB中的Node.jsdate对象为“1970-01-01T00:00:00.001Z”
- 使用正则expression式来比较mongodb中的车辆号码
- Mongoose是不是可扩展的文档数组编辑和版本控制?
- MongoError:找不到任何特殊的索引:2d(需要索引),2dsphere(需要索引)$ nearSphere
- Nodejs / Express – 启动我的应用程序:express.createServer()已弃用
- 帆在两个模型中插入相同的对象