0

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

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Cool sir, this one works. Thank you. In my case, as I needed to add 1 more condition to check along with price, I had to add an &&. So finally my update looks like this. var update = Builders<Book>.Update.PullFilter(p => p.authors, f => (f.price == x.price && f.author == x.author ));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.