How to remove nested array element in mongodb document using C # driver

I am new to the world of Mongodb, and now I am struggling with how I can remove, update an element in the nested field of the document array. Here is my samle document:

{ "_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" } ] } 

In my method, I get the document identifier and the identifier (Identifier) ​​of the Product that I want to delete. Can someone tell me how I can remove the item with the identifier: 170220151653 from the "Products" field?

I tried:

 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); 

as suggested here: MongoDB removes a subdocument document from a subdocument

But I get an error

myDb.Applications ()

It is simply impossible to find.

SOLVE:

 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); 
+6
source share
3 answers

You call the Pull(string name, MongoDB.Bson.BsonValue value) method Pull(string name, MongoDB.Bson.BsonValue value) and as per the docs

Removes all values ​​from a named element of an array that are equal to some value (see $ pull)

and you provide { "Identifier", productId } as a value. I think that mango does not find the exact meaning.

Try using a second Pull overload with a query condition instead of an exact value

Removes all values ​​from the named element of the array that match the request (see $ pull).

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

UPDATE

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

 var pull = Update<Category>.Pull(x => x.Products, builder => builder.Where(q => q.Identifier == productId)); 
+9
source

Hi, according to my understanding, you want to remove the whole consistent elements of the given identifier and identifier, so the request below can solve your problem, but I don’t know how to convert it to C# , here mongo $ pull should be used.

  db.collectionName.update({"_id" : ObjectId("55f354533dd61e5004ca5208")}, {"$pull":{"Products":{"Identifier":"170220151653"}}}) 
+1
source

I also ran into the same problem, and then finally, after repeated R&D, I found out that you need to use PullFilter instead of Pull when you want to remove using a filter.

0
source

Source: https://habr.com/ru/post/982682/


All Articles