在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
需要引用MongoDB.Driver.dll、MongoDB.Driver.core.dll、MongoDB.Bson.dll三个dll。 1、数据库连接: public class MongoDb { //方式一 //private static readonly string connStr = "mongodb://myAdmin:123456@localhost"; //private static readonly string dbName = "myTest"; //方式二(myTestAdmin用户只可访问数据库myTest) private static readonly string connStr = "mongodb://myTestAdmin:123456@localhost/myTest"; private static IMongoDatabase db = null; private static readonly object lockHelper = new object(); private MongoDb() { } public static IMongoDatabase GetMongoDb() { if (db == null) { lock (lockHelper) { if (db == null) { //方式一 //var client = new MongoClient(connStr); //db = client.GetDatabase(dbName); //方式二(myTestAdmin用户只可访问数据库myTest) var url = new MongoUrl(connStr); MongoClientSettings mcs = MongoClientSettings.FromUrl(url); mcs.MaxConnectionLifeTime = TimeSpan.FromMilliseconds(1000); var client = new MongoClient(mcs); db = client.GetDatabase(url.DatabaseName); } } } return db; } } 2、插入操作: class Program { static void Main(string[] args) { IMongoDatabase db = MongoDb.GetMongoDb(); var collection = db.GetCollection<BsonDocument>("userInfo"); //插入 var document = new BsonDocument { { "name", "Liming" }, { "age", "23" }, { "score", new BsonDocument { { "yuwen", 115 }, { "shuxue", 135 }, { "yingyu", 120 } }} }; collection.InsertOne(document); Console.ReadKey(); } } Robomongo中查看结果:
3、查询操作: class Program { static void Main(string[] args) { IMongoDatabase db = MongoDb.GetMongoDb(); var collection = db.GetCollection<BsonDocument>("userInfo"); //查询 var document = collection.Find(new BsonDocument()).FirstOrDefault(); Console.WriteLine(document.ToString()); Console.ReadKey(); } }
4、更新操作: class Program { static void Main(string[] args) { IMongoDatabase db = MongoDb.GetMongoDb(); var collection = db.GetCollection<BsonDocument>("userInfo"); //更新 var filter = Builders<BsonDocument>.Filter.Eq("age", "23"); var update = Builders<BsonDocument>.Update.Set("age", "30"); collection.UpdateOne(filter, update); Console.ReadKey(); } }
5、删除操作: class Program { static void Main(string[] args) { IMongoDatabase db = MongoDb.GetMongoDb(); var collection = db.GetCollection<BsonDocument>("userInfo"); //删除 var filter1 = Builders<BsonDocument>.Filter.Eq("age", "30"); collection.DeleteOne(filter1); Console.ReadKey(); } }
参考:http://mongodb.github.io/mongo-csharp-driver/2.5/getting_started/quick_tour/
上面操作的集合类型都是BsonDocument, 下面可以自定义实体类,mongodb可以直接返回对应自定义类的集合或者对象: |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论