0

I have this code that pulls multiple elements from the 'fruits' array and it does it for all the 'stores' in the database:

db.stores.update(
  { },
  { $pull: { fruits: { $in: [ "apples", "bananas" ] } } },
  { multi: true }
)

How can I transfer this to C# code using .Net Driver? UpdateManyAsync method should be used from namespace MongoDB.Driver IMongoCollection but I don't know how to do the specific filtering.

1
  • mongo driver allows implicit conversion between string and most of parameters, so you can just put a string { $pull: { fruits: { $in: [ "apples", "bananas" ] } } } into appropriate UpdateManyAsync argument Commented Oct 1, 2021 at 22:32

1 Answer 1

1

Mongo .NET driver support scripting with untyped document (BsonDocument).

UpdateMany

Update many documents, equivalent to { multi: true }

You can achieve as below:

MongoClient _client = new MongoClient("mongo connection string");

IMongoDatabase _database = _client.GetDatabase("your DB");
IMongoCollection<Store> _collection = _database.GetCollection<Store>("store");

string[] removedFruits = new string[] { "apples", "bananas" };
FilterDefinition<Store> filter = Builders<Store>.Filter.Empty;

UpdateDefinition<Store> update =
    new BsonDocument("$pull",
        new BsonDocument("fruits",
            new BsonDocument("$in", BsonArray.Create(removedFruits))
        )
    );

_collection.UpdateMany(filter, update);
public class Store
{
    public string[] Fruits { get; set; }

    // Other properties
}
Sign up to request clarification or add additional context in comments.

1 Comment

This solution solved the probelm, thank you very much :)

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.