Mongodb 學習筆記(三) .net core SDK

 首先添加 Nuget包  MongoDB.Drivermongodb

 建立一個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創建鏈接:ui

 var client = new MongoClient("mongodb://127.0.0.1:27017");   //與Mongodb創建鏈接。
 var db = client.GetDatabase("test");  //獲取數據庫
 var collection = db.GetCollection<BsonDocument>("student");   //選擇操做集合

 增刪改查:spa

 1  Student student = new Student()
 2  {
 3    name = "lilie",
 4    age = 11,
 5    address = new Address() { province = "GuangDong",city "shenzhen"}
 6  };
 7  
 8  collection.InsertOne(student.ToBsonDocument()); //插入數據
 9  var filter = Builders<BsonDocument>.Filter.Eq("name", "lilie"); //聲明過濾條件
10  var list = collection.Find(filter).As<Student>().ToList();  //查詢數據
11  collection.UpdateOne(filter,Builders<BsonDocument>.Update.Set("age", "24")); //更新數據
12  collection.DeleteOne(filter); //刪除數據
相關文章
相關標籤/搜索