我是
Mongodb世界的新手,现在我正在努力如何删除,更新文档的嵌套数组字段中的元素.这是我的samle文件:
{ "_id" : ObjectId("55f354533dd61e5004ca5208"),"Name" : "Hand made products for real!","Description" : "Products all made by hand","Products" : [ { "Identifier" : "170220151653","Price" : 20.5,"Name" : "Leather bracelet","Description" : "The bracelet was made by hand","ImageUrl" : "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQii6JCvXtx0iJGWgpvSl-KrdZONKYzDwS0U8uDvUunjO6BO9Aj" } ] }
在我的方法中,我得到了文档的id和我想删除的Product的id(Identifier).任何人都可以告诉我如何从Products字段中删除具有Identifier的元素:170220151653?
我试过了:
var query = Query.And(Query.EQ("_id",categoryId),Query.EQ("Products.Identifier",productId)); var update = Update.Pull("Products",new BsonDocument(){{ "Identifier",productId }}); myDb.Applications().Update(query,update);
正如这里建议的那样:MongoDB remove a subdocument document from a subdocument
但我得到一个错误
myDb.Applications()
它无法找到.
解决了:
var pull = Update<Category>.Pull(x => x.Products,builder => builder.EQ(q => q.Identifier,productId)); collection.Update(Query.And(Query.EQ("_id",ObjectId.Parse(categoryId)),productId)),pull);
解决方法
你正在调用方法Pull(字符串名称,MongoDB.Bson.BsonValue值)并根据文档它
Removes all values from the named array element that are equal to some
value (see $pull)
并提供{“Identifier”,productId}作为值.我猜mongo没有找到确切的值.
尝试使用带有查询条件的Pull的第二个重载而不是精确值
Removes all values from the named array element that match some query
(see $pull).
var update = Update.Pull("Products",Query.EQ("Identifier",productId));
UPDATE
既然你提到了Category实体,那么我可以建议使用lambda而不是
Query.EQ:
var pull = Update<Category>.Pull(x => x.Products,builder => builder.Where(q => q.Identifier == productId));