How can I delete nested array element in a mongodb document with the c# driver

前端 未结 6 1754
没有蜡笔的小新
没有蜡笔的小新 2021-02-14 08:21

I am new in the MongoDB world and now I am struggling of how can I delete, update element in a nested array field of a document. Here is my sample document:

{
           


        
6条回答
  •  梦谈多话
    2021-02-14 08:37

    You are calling method Pull(string name, MongoDB.Bson.BsonValue value) and according to the docs it

    Removes all values from the named array element that are equal to some value (see $pull)

    and you provide { "Identifier", productId } as the value. I guess that mongo does not find that exact value.

    Try to use the second overload of Pull with query-condition instead of exact value

    Removes all values from the named array element that match some query (see $pull).

    var update = Update.Pull("Products", Query.EQ("Identifier", productId));
    

    UPDATE

    Since you mention Category entity so I can suggest using lambda instead of Query.EQ:

    var pull = Update.Pull(x => x.Products, builder =>
    builder.Where(q => q.Identifier == productId));
    

提交回复
热议问题