- UpdateMany 批量更新,UpdateOne更新一个
var connectionString = "mongodb://localhost:27017"; var client = new MongoClient(connectionString); var database = client.GetDatabase("School"); var collection = database.GetCollection<StudentNew>("StudentNew"); var filter = Builders<StudentNew>.Filter.Where(m => m.Sex =="男"); var update = Builders<StudentNew>.Update.Set(m => m.Name, "隔壁老王"); collection.UpdateMany(filter, update); await collection.Find(x => x.Sex =="男") .Sort("{Age:1}") .Project("{Name:1}") .ForEachAsync(student => { Console.WriteLine(student); }); class StudentNew { public ObjectId _id { get; set; } public string Name { get; set; } public string Age { get; set; } public IEnumerable<string> Address { get; set; } public string Sex { get; set; } }
- 批量删除DeleteMany,单个删除DeleteOne
var connectionString = "mongodb://localhost:27017"; var client = new MongoClient(connectionString); var database = client.GetDatabase("School"); var collection = database.GetCollection<StudentNew>("StudentNew"); var filter = Builders<StudentNew>.Filter.Where(m => m.Sex =="男"); collection.DeleteMany(filter); //collection.DeleteOne(filter); await collection.Find(FilterDefinition<StudentNew>.Empty) .Sort("{Age:1}") .Project("{Name:1}") .ForEachAsync(student => { Console.WriteLine(student); }); class StudentNew { public ObjectId _id { get; set; } public string Name { get; set; } public string Age { get; set; } public IEnumerable<string> Address { get; set; } public string Sex { get; set; } }