2.C#操作MongoDB(详细)

1.连接数据库

要连接数据库,首先需要指定要连接的数据库名称,如果数据库不存在的话,MongoDB 则会自动创建它。下面通过简单的代码来演示如何使用C#代码连接 MongoDB 数据库:

using System;
using MongoDB.Driver;

namespace MongoDBDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = "mongodb://127.0.0.1:27017/bianchengbang";
            MongoClient mongoClient = new MongoClient(connectionString);

            MongoCredential credential;
            credential = MongoCredential.CreateCredential("sampleUser", "myDb", "password");
            Console.WriteLine("Connected to the database successfully!");

            IMongoDatabase database = mongoClient.GetDatabase("myDB");
            Console.WriteLine("Credentials ::" + credential);

            Console.ReadKey();
        }
    }
}

编译并运行上面的程序,即可创建名为“myDb”的数据库,并输出如下所示的内容:

Connected to the database successfully!
Credentials ::myDb@sampleUser

2.创建集合

若要创建集合,您可以使用 com.mongodb.client.MongoDatabase 类的 createCollection() 方法,示例代码如下:

using System;
using MongoDB.Driver;

namespace MongoDBDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = "mongodb://127.0.0.1:27017/bianchengbang";
            MongoClient mongoClient = new MongoClient(connectionString);

            MongoCredential credential;
            credential = MongoCredential.CreateCredential("sampleUser", "myDb", "password");
            Console.WriteLine("Connected to the database successfully!");

            IMongoDatabase database = mongoClient.GetDatabase("myDB");

            database.CreateCollection("tutorial");
            Console.WriteLine("Create collection successfully!");

            Console.ReadKey();
        }
    }
}

编译并运行上面的程序,运行结果如下所示:

Connected to the database successfully!
Create collection successfully!

3.获取/选择集合

要获取/选择数据库中的集合,您可以使用 com.mongodb.client.MongoDatabase 类的 getCollection() 方法,示例代码如下:

using System;
using MongoDB.Bson;
using MongoDB.Driver;

namespace MongoDBDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = "mongodb://127.0.0.1:27017/bianchengbang";
            MongoClient mongoClient = new MongoClient(connectionString);

            MongoCredential credential;
            credential = MongoCredential.CreateCredential("sampleUser", "myDb", "password");
            Console.WriteLine("Connected to the database successfully!");

            IMongoDatabase database = mongoClient.GetDatabase("myDB");

            database.CreateCollection("tutorial2");
            Console.WriteLine("Create collection successfully!");

            const string collectionName = "tutorial2";
            var collection = database.GetCollection<BsonDocument>(collectionName);
            Console.WriteLine("Select collection tutorial2 successfully!");

            Console.ReadKey();
        }
    }
}

编译并运行上面的程序,运行结果如下所示:

Connected to the database successfully!
Create collection successfully!
Select collection tutorial2 successfully!

4.插入文档

想要向集合中插入文档,您可以使用 com.mongodb.client.MongoCollection 类的 insert() 方法,示例代码如下:

using System;
using MongoDB.Bson;
using MongoDB.Driver;

namespace MongoDBDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = "mongodb://127.0.0.1:27017/bianchengbang";
            MongoClient mongoClient = new MongoClient(connectionString);
            IMongoDatabase database = mongoClient.GetDatabase("myDB");

            const string collectionName = "tutorial3";
            database.CreateCollection(collectionName);
            Console.WriteLine("Create collection successfully!");

            var collection = database.GetCollection<BsonDocument>(collectionName);
            Console.WriteLine("Select collection successfully!");

            BsonDocument document = new BsonDocument("title", "MongoDB")
                .Add("description", "database")
                .Add("likes", 100)
                .Add("url", "www.bianchengbang.net")
                .Add("by", "编程帮");
            collection.InsertOne(document);
            Console.WriteLine("Insert document successfully");

            Console.ReadKey();
        }
    }
}

Create collection successfully!
Select collection successfully!
Insert document successfully

5.查询文档

想要查询集合中的文档,您可以使用 com.mongodb.client.MongoCollection 类的 find() 方法,此方法会返回一个游标,因此想要查询集合中的所有文档您只需要不断迭代此游标即可,示例代码如下:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;

namespace MongoDBDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = "mongodb://127.0.0.1:27017/bianchengbang";
            MongoClient mongoClient = new MongoClient(connectionString);

            MongoCredential credential;
            credential = MongoCredential.CreateCredential("sampleUser", "myDb", "password");
            Console.WriteLine("Connected to the database successfully!");

            IMongoDatabase database = mongoClient.GetDatabase("myDB");

            const string collectionName = "tutorial3";
            var collection = database.GetCollection<BsonDocument>(collectionName);
            Console.WriteLine("Select collection successfully!");

            BsonDocument document1 = new BsonDocument("title", "MongoDB")
                .Add("description", "database")
                .Add("likes", 100)
                .Add("url", "www.bianchengbang.net")
                .Add("by", "编程帮");
            BsonDocument document2 = new BsonDocument("title", "html")
                .Add("description", "database")
                .Add("likes", 200)
                .Add("url", "www.bianchengbang.net/html")
                .Add("by", "编程帮");
            List<BsonDocument> list = new List<BsonDocument>();
            list.Add(document1);
            list.Add(document2);
            collection.InsertMany(list);

            var filter = new BsonDocument();
            var list2 = Task.Run(async () => await collection.Find(filter).ToListAsync()).Result;
            list2.ForEach(p =>
            {
                Console.WriteLine(p);
            });

            Console.ReadKey();
        }
    }
}

Connected to the database successfully!
Select collection successfully!
{ “_id” : ObjectId(“62cb94d1c6343689168a3979”), “title” : “MongoDB”, “description” : “database”, “likes” : 100, “url” : “www.bianchengbang.net”, “by” : “编程帮” }
{ “_id” : ObjectId(“62cbbcc68b693b007da230d9”), “title” : “MongoDB”, “description” : “database”, “likes” : 100, “url” : “www.bianchengbang.net”, “by” : “编程帮” }
{ “_id” : ObjectId(“62cbbcc68b693b007da230da”), “title” : “html”, “description” : “database”, “likes” : 200, “url” : “www.bianchengbang.net/html”, “by” : “编程帮” }

6.更新文档

要更新(修改)集合中文档的数据,您可以使用 com.mongodb.client.MongoCollection 类的 updateOne() 方法,示例代码如下:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;

namespace MongoDBDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = "mongodb://127.0.0.1:27017/bianchengbang";
            MongoClient mongoClient = new MongoClient(connectionString);

            MongoCredential credential;
            credential = MongoCredential.CreateCredential("sampleUser", "myDb", "password");
            Console.WriteLine("Connected to the database successfully!");
            IMongoDatabase database = mongoClient.GetDatabase("myDB");

            const string collectionName = "tutorial3";
            var collection = database.GetCollection<BsonDocument>(collectionName);
            Console.WriteLine("Select collection successfully!");

            var filter = Builders<BsonDocument>.Filter.Eq("title", "html");
            var update = Builders<BsonDocument>.Update
                .Set("likes", 520)
                .CurrentDate("lastModified");
            collection.UpdateOne(filter, update);
            Console.WriteLine("Update document successfully!");

            var filter2 = new BsonDocument();
            var list = Task.Run(async () => await collection.Find(filter2).ToListAsync()).Result;
            list.ForEach(p =>
            {
                Console.WriteLine(p);
            });

            Console.ReadKey();
        }
    }
}

Connected to the database successfully!
Select collection successfully!
Update document successfully!
{ “_id” : ObjectId(“62cb94d1c6343689168a3979”), “title” : “MongoDB”, “description” : “database”, “likes” : 100, “url” : “www.bianchengbang.net”, “by” : “编程帮” }
{ “_id” : ObjectId(“62cbbcc68b693b007da230d9”), “title” : “MongoDB”, “description” : “database”, “likes” : 100, “url” : “www.bianchengbang.net”, “by” : “编程帮” }
{ “_id” : ObjectId(“62cbbcc68b693b007da230da”), “title” : “html”, “description” : “database”, “likes” : 520, “url” : “www.bianchengbang.net/html”, “by” : “编程帮”, “lastModified” : ISODate(“2022-07-11T06:50:03.421Z”) }

7.删除文档

想要从集合中删除文档,您可以使用 com.mongodb.client.MongoCollection 类的 deleteOne() 方法,示例代码如下:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;

namespace MongoDBDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = "mongodb://127.0.0.1:27017/bianchengbang";
            MongoClient mongoClient = new MongoClient(connectionString);

            MongoCredential credential;
            credential = MongoCredential.CreateCredential("sampleUser", "myDb", "password");
            Console.WriteLine("Connected to the database successfully!");
            IMongoDatabase database = mongoClient.GetDatabase("myDB");

            const string collectionName = "tutorial3";
            var collection = database.GetCollection<BsonDocument>(collectionName);
            Console.WriteLine("Select collection successfully!");

            var filter = Builders<BsonDocument>.Filter.Eq("title", "MongoDB");
            collection.DeleteOne(filter);
            Console.WriteLine("Delete document successfully!");

            var filter2 = new BsonDocument();
            var list = Task.Run(async () => await collection.Find(filter2).ToListAsync()).Result;
            list.ForEach(p =>
            {
                Console.WriteLine(p);
            });

            Console.ReadKey();
        }
    }
}

Connected to the database successfully!
Select collection successfully!
Delete document successfully!
{ “_id” : ObjectId(“62cbbcc68b693b007da230d9”), “title” : “MongoDB”, “description” : “database”, “likes” : 100, “url” : “www.bianchengbang.net”, “by” : “编程帮” }
{ “_id” : ObjectId(“62cbbcc68b693b007da230da”), “title” : “html”, “description” : “database”, “likes” : 520, “url” : “www.bianchengbang.net/html”, “by” : “编程帮”, “lastModified” : ISODate(“2022-07-11T06:50:03.421Z”) }

8.删除集合

要从数据库中删除集合,您可以使用 com.mongodb.client.MongoCollection 类中的 drop() 方法,示例代码如下:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;

namespace MongoDBDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = "mongodb://127.0.0.1:27017/bianchengbang";
            MongoClient mongoClient = new MongoClient(connectionString);

            MongoCredential credential;
            credential = MongoCredential.CreateCredential("sampleUser", "myDb", "password");
            Console.WriteLine("Connected to the database successfully!");
            IMongoDatabase database = mongoClient.GetDatabase("myDB");
            
            const string collectionName = "tutorial";
            Task.Run(async () =>
            {
                await database.DropCollectionAsync(collectionName);
            });
            Console.WriteLine("Drop collection successfully!");

            Console.ReadKey();
        }
    }
}

Connected to the database successfully!
Drop collection successfully!

9.列出所有集合
using System;
using MongoDB.Driver;

namespace MongoDBDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = "mongodb://127.0.0.1:27017/bianchengbang";
            MongoClient mongoClient = new MongoClient(connectionString);

            MongoCredential credential;
            credential = MongoCredential.CreateCredential("sampleUser", "myDb", "password");
            Console.WriteLine("Connected to the database successfully!");
            IMongoDatabase database = mongoClient.GetDatabase("myDB");

            var list = database.ListCollectionNames().ToList();
            foreach (var item in list)
            {
                Console.WriteLine(item);
            }

            Console.ReadKey();
        }
    }
}

Connected to the database successfully!
tutorial3
tutorial1
tutorial2

  • 2
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
C# 中使用 MongoDB 进行查询操作,需要使用 MongoDBC# 驱动程序,该驱动程序提供了一组 API 用于实现查询操作。下面我们来分别介绍这些查询操作: 1. 等于查询 等于查询是最常用的查询操作,它用于查询指定字段等于指定值的文档。在 C# 中实现等于查询,可以使用下面的代码: ```c# var filter = Builders<BsonDocument>.Filter.Eq("field", "value"); var result = collection.Find(filter).ToList(); ``` 其中,`field` 是要查询的字段名,`value` 是要查询的值。`Builders<BsonDocument>.Filter.Eq` 方法用于创建等于查询的过滤器,`collection.Find` 方法用于执行查询操作。 2. 大于查询和小于查询 大于查询和小于查询分别用于查询指定字段大于或小于指定值的文档。在 C# 中实现大于查询和小于查询,可以使用下面的代码: ```c# // 大于查询 var filter = Builders<BsonDocument>.Filter.Gt("field", "value"); var result = collection.Find(filter).ToList(); // 小于查询 var filter = Builders<BsonDocument>.Filter.Lt("field", "value"); var result = collection.Find(filter).ToList(); ``` 其中,`Builders<BsonDocument>.Filter.Gt` 方法用于创建大于查询的过滤器,`Builders<BsonDocument>.Filter.Lt` 方法用于创建小于查询的过滤器。 3. 大于等于查询和小于等于查询 大于等于查询和小于等于查询分别用于查询指定字段大于等于或小于等于指定值的文档。在 C# 中实现大于等于查询和小于等于查询,可以使用下面的代码: ```c# // 大于等于查询 var filter = Builders<BsonDocument>.Filter.Gte("field", "value"); var result = collection.Find(filter).ToList(); // 小于等于查询 var filter = Builders<BsonDocument>.Filter.Lte("field", "value"); var result = collection.Find(filter).ToList(); ``` 其中,`Builders<BsonDocument>.Filter.Gte` 方法用于创建大于等于查询的过滤器,`Builders<BsonDocument>.Filter.Lte` 方法用于创建小于等于查询的过滤器。 4. 包含查询 包含查询用于查询指定字段包含指定值的文档。在 C# 中实现包含查询,可以使用下面的代码: ```c# var filter = Builders<BsonDocument>.Filter.In("field", new BsonArray { "value1", "value2", "value3" }); var result = collection.Find(filter).ToList(); ``` 其中,`new BsonArray { "value1", "value2", "value3" }` 是要查询的值列表,`Builders<BsonDocument>.Filter.In` 方法用于创建包含查询的过滤器。 5. 不包含查询 不包含查询用于查询指定字段不包含指定值的文档。在 C# 中实现不包含查询,可以使用下面的代码: ```c# var filter = Builders<BsonDocument>.Filter.Nin("field", new BsonArray { "value1", "value2", "value3" }); var result = collection.Find(filter).ToList(); ``` 其中,`new BsonArray { "value1", "value2", "value3" }` 是要查询的值列表,`Builders<BsonDocument>.Filter.Nin` 方法用于创建不包含查询的过滤器。 以上是 MongoDB 中常用的几种查询操作,在 C# 中可以使用 MongoDBC# 驱动程序实现。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Kerven_HKW

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

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

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

打赏作者

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

抵扣说明:

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

余额充值