<七>.netcore更新删除MongoDB

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

 

posted @ 2022-06-16 23:36  许轩霖  阅读(101)  评论(0编辑  收藏  举报