我是MongoDB世界的新手,现在我正苦恼于如何删除、更新文档中嵌套数组字段中的元素。这是我的示例文档:
{
"_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和我想要删除的产品的ID(标识符)。请问有人能告诉我如何从“产品”字段中删除具有标识符为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从子文档中删除一个子文档
但是在
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)), Query.EQ("Products.Identifier", productId)), pull);
标识符
还是整个数组? - Neo-coder