加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何使用c#驱动程序删除mongodb文档中的嵌套数组元素

发布时间:2020-12-15 08:27:31 所属栏目:百科 来源:网络整理
导读:我是 Mongodb世界的新手,现在我正在努力如何删除,更新文档的嵌套数组字段中的元素.这是我的samle文件: { "_id" : ObjectId("55f354533dd61e5004ca5208"),"Name" : "Hand made products for real!","Description" : "Products all made by hand","Products"
我是 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));

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读