0)基本准备
安装MongoDB驱动(当前文章是基于MongoDB.Driver.dll, v1.7.0.4714)
using MongoDB.Bson; using MongoDB.Driver;
1)创建连接
#0)准备连接字符串及db private static readonly string _connectionString = "mongodb://localhost"; private static readonly string _dbName = "test"; //1)创建connection var _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);
时间: 2024-12-16 00:02:02