Naresh
Naresh

Reputation: 678

Removing a document from array of documents in mongodb using c#

I want to remove the highest value price document

{
    "name" : "Ryan",
    "price" : 6.5
}

from

db.books.find({_id:5}).pretty()
{
    "_id" : 5,
    "name" : "Big Book",
    "authors" : [
        {
            "name" : "Ryan",
            "price" : 5.5
        },
        {
            "name" : "Ryan",
            "price" : 6.5
        }
    ]
}

using c# driver

I have the removable document in c# front end in a collection.

But my following update statement is not removing the document.

var filter = new BsonDocument("_id", x._id);
var docToRemove = new BsonDocument("name", x.name);docToRemove.Add("price", x.price);
var update = Builders<Book>.Update.Pull("books.authors", docToRemove);
var result = await col.FindOneAndUpdateAsync(filter, update);

Upvotes: 0

Views: 940

Answers (1)

marcinax
marcinax

Reputation: 1195

Do you have required value in x.price?

I didn't test it for exactly your case, but try this:

var update = Builders<Book>.Update.PullFilter(p => p.authors,
                                              f => f.price == x.price);
var result = await collection.FindOneAndUpdateAsync(p => p._id == 5, update);

Upvotes: 2

Related Questions