我是 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(Identifier)。谁能告诉我如何从 Products 字段中删除具有标识符的元素: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)), Query.EQ("Products.Identifier", productId)), pull);
最佳答案
您正在调用方法 Pull(string name, MongoDB.Bson.BsonValue value)
并根据文档
Removes all values from the named array element that are equal to some value (see $pull)
并且您提供 { "Identifier", productId }
作为值。我猜 mongo 没有找到那个 exact 值。
尝试将 Pull
的第二个重载与查询条件一起使用而不是精确值
Removes all values from the named array element that match some query (see $pull).
var update = Update.Pull("Products", Query.EQ("Identifier", productId));
更新
既然你提到了 Category
实体,所以我可以建议使用 lambda 而不是
Query.EQ
:
var pull = Update<Category>.Pull(x => x.Products, builder =>
builder.Where(q => q.Identifier == productId));
https://stackoverflow.com/questions/28585206/
相关文章:
node.js - Mongoose - findByIdAndUpdate - 不适用于 req.
java - 在最新的 MongoDB java 驱动程序中使用 createIndex() 时,索
java - Mongodb选择所有字段按一个字段分组并按另一个字段排序
java - MongoDB Java 驱动程序 : distinct with sort
javascript - 在 MongoDB 更新语句中使用变量
mongodb - Meteor.Collection 和 Meteor.Collection.Cu
ruby-on-rails - Mongoid 批量更新/Upsert 替代方案?