Mongodb 学习笔记(三) .net core SDK

时间:2023-03-09 14:29:42
Mongodb 学习笔记(三)  .net core SDK

首先添加 Nuget包  MongoDB.Driver

 创建一个Model。

public class Student {

    public ObjectId _id { get; set; }
public string name { get; set; }
public int age { get; set; }
public Address address { get; set; }
}
public class Address{
public string province { get; set; }
public string city { get; set; }
}

 与Mongodb建立连接:

 var client = new MongoClient("mongodb://127.0.0.1:27017");   //与Mongodb建立连接。
 var db = client.GetDatabase("test");  //获取数据库
 var collection = db.GetCollection<BsonDocument>("student"); //选择操作集合

 增删改查:

  Student student = new Student()
{
  name = "lilie",
   age = ,
  address = new Address() { province = "GuangDong",city "shenzhen"}
}; collection.InsertOne(student.ToBsonDocument()); //插入数据
var filter = Builders<BsonDocument>.Filter.Eq("name", "lilie"); //声明过滤条件
var list = collection.Find(filter).As<Student>().ToList(); //查询数据
collection.UpdateOne(filter,Builders<BsonDocument>.Update.Set("age", "")); //更新数据
collection.DeleteOne(filter); //删除数据