Search code examples
c#.netmongodbmongodb-.net-driver

MongoDB .Net Driver - Pull multiple elements from arrays that exist in multiple documents


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.


Solution

  • 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
    }