.NET 操作MongoDB入門(三)最簡單的增刪改查操作
阿新 • • 發佈:2018-12-23
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using MongoDB.Driver; using MongoDB.Bson; namespace MongoDBTest { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { Mongo(); } public void Mongo() { //建立連線 var client = new MongoClient(); //建立資料庫 var database = client.GetDatabase("TestDb"); //建立collection var collection = database.GetCollection("foo"); var document = new BsonDocument { {"name","MongoDB"}, {"type","Database"}, {"count",1}, {"info",new BsonDocument{{"x",203},{"y",102}}} }; //插入資料 collection.InsertOne(document); var count = collection.Count(document); Console.WriteLine(count); //查詢資料 var document1 = collection.Find(document); Console.WriteLine(document1.ToString()); //更新資料 var filter = Builders.Filter.Eq("name", "MongoDB"); var update = Builders.Update.Set("name", "Ghazi"); collection.UpdateMany(filter, update); //刪除資料 var filter1 = Builders.Filter.Eq("count", 101); collection.DeleteMany(filter1); BsonDocument document2 = new BsonDocument(); document2.Add("name", "MongoDB"); document2.Add("type", "Database"); document2.Add("count", "1"); collection.InsertOne(document2); } } }