2025年3月18日 星期二 甲辰(龙)年 月十七 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > .net

C#访问MongoDB并执行CRUD操作

时间:04-19来源:作者:点击数:39

先在NuGet中下载并安装驱动mongocsharpdriver,和客户端包MongoDB.Driver

代码如下

  • using MongoDB.Bson;
  • using MongoDB.Bson.Serialization;
  • using MongoDB.Driver;
  • using MongoDB.Driver.Builders;
  • namespace TestMongoDB
  • {
  • [Serializable]
  • class Customer
  • {
  • public int id { set; get; }
  • public string name { set; get; }
  • public int age { set; get; }
  • }
  • class Program
  • {
  • public static void Main()
  • {
  • MongoClient client;
  • MongoServer server;
  • client = new MongoClient("mongodb://admin:Abc12345@localhost:27017/admin");
  • if (client != null)
  • {
  • Console.WriteLine("MongoDB connect success.");
  • server = client.GetServer();
  • MongoDatabase mdb = server.GetDatabase("foo");
  • MongoCollection<BsonDocument> collection = mdb.GetCollection("bar");
  • // Select operation
  • var records = collection.FindAll();
  • foreach (BsonDocument record in records)
  • {
  • Console.WriteLine(record);
  • }
  • // Insert operation
  • Customer customer = new Customer
  • {
  • id = 8,
  • name = "zahngsan",
  • age = 28
  • };
  • collection.Insert<Customer>(customer);
  • // Update operation
  • IMongoQuery iq4u = Query.EQ("name", "zhangsan_1");
  • IMongoUpdate iu = Update.Set("name", "zhangsan").Set("age", 98);
  • collection.Update(iq4u, iu, UpdateFlags.Multi);
  • // Delete operation
  • IMongoQuery iq4d = Query.EQ("name", "zhangsan_2");
  • collection.Remove(iq4d);
  • // Select as Object
  • /*MongoCollection<Customer> collection2 = mdb.GetCollection<Customer>("bar");
  • var customer1 = collection2.FindOne();
  • var customer2 = collection2.FindOneAs<Customer>();
  • foreach (BsonDocument record in records)
  • {
  • var customer3 = BsonSerializer.Deserialize<Customer>(record);
  • }*/
  • }
  • else
  • {
  • Console.WriteLine("MongoDB connect fail.");
  • }
  • }
  • }
  • }
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门