Home > other >  Can I pull multiple elements from arrays that exist in multiple documents in C# .Net Driver
Can I pull multiple elements from arrays that exist in multiple documents in C# .Net Driver

Time:10-04

I have this code which pulls multiple elements from 'fruits' array and it does it for all the 'stores' in 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 dont know how to do the specific filtering.

CodePudding user response:

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