C#访问MongoDB并执行CRUD操作

先在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.");
            }
        }
	}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

皓月如我

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值