標籤:
0)基本準備
安裝MongoDB驅動(當前文章是基於MongoDB.Driver.dll, v1.7.0.4714)
using MongoDB.Bson;using MongoDB.Driver;
1)建立串連
#0)準備連接字串及dbprivate static readonly string _connectionString = "mongodb://localhost";private static readonly string _dbName = "test";//1)建立connectionvar _mongoClient = new MongoClient(_connectionString);var _server = _mongoClient.GetServer();var _db = _server.GetDatabase(_dbName);var collection = _db.GetCollection("redpack");
2)實現增刪
Dictionary<string, string> contact = new Dictionary<string, string>;contact.Add("mch_billno", "12345678");contact.Add("pername", "王墨");contact.Add("sex", "男");contact.Add("age", "35");//2)插入BsonDocument doc = new BsonDocument();doc.SetDocumentId(contact["mch_billno"]);//為了自己實現維護doc.Add(contact);collection.Insert(doc);//3)更新var query = new QueryDocument { { "_id", contact["mch_billno"] } };var updateBson = new BsonDocument();updateBson.Add(contact);var updateDocument = new UpdateDocument { { "$set", updateBson }};collection.Update(query, updateDocument);
.Net使用MongoDB初體驗