MongoDB是一个基于分布式文件存储 [1] 的数据库。由C++语言编写。旨在为WEB应用提供可扩展的高性能数据存储解决方案。本文主要介绍.NET(C#)中使用MongoDB的配置,和增、删、改、查的使用方法,以及相关的示例代码。

1、安装引用MongoDB.Driver

1)使用Nuget界面管理器

直接搜索 "MongoDB.Driver",找到对应的点安装即可。

相关文档VS(Visual Studio)中Nuget的使用

2)使用Package Manager命令安装

PM> Install-Package MongoDB.Driver

3)使用.NET CLI命令安装

> dotnet add package MongoDB.Driver

2、配置MongoDB的连接字符串

MongoDB中配置连接对象,可以使用帐号和密码验证,也可以不用,相关配置代码如下,

1)不验证帐号和密码

var client = new MongoClient("mongodb://localhost:27017");          

2)验证帐号和密码

var client = new MongoClient("mongodb://localhost:27017");
string user = "root";
string password = "Aa123456";
var credential = MongoCredential.CreateMongoCRCredential("admin", user, password);
var settings = new MongoClientSettings { Credentials = new[] { credential } };
var mongoClient = new MongoClient(settings);         

3、MongoDB中数据常用操作

MongoDB中增、删、改、查常用操作,可以参考如下代码:

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

namespace MongoDBCRUDExample
{
    class Program
    {
        static void Main(string[] args)
        {
            var client = new MongoClient("mongodb://localhost:27017");
            /*
             var client = new MongoClient("mongodb://localhost:27017");
             string password = "Aa123456";
             var credential = MongoCredential.CreateMongoCRCredential("admin", user, password);
             var settings = new MongoClientSettings { Credentials = new[] { credential } };
             var mongoClient = new MongoClient(settings);
             */

            /*****新增*****/
            var database = client.GetDatabase("MyDB");
            var collection = database.GetCollection<BsonDocument>("students");
            var document = new BsonDocument { { "student_id", 10000 }, {
                "scores",
                new BsonArray {
                new BsonDocument { { "type", "exam" }, { "score", 88.12334193287023 } },
                new BsonDocument { { "type", "math" }, { "score", 74.92381029342834 } },
                new BsonDocument { { "type", "homework" }, { "score", 89.97929384290324 } },
                new BsonDocument { { "type", "homework" }, { "score", 82.12931030513218 } }

                }
                }, { "class_id", 480 }
        };
            collection.InsertOne(document);
            // await collection.InsertOneAsync(document);//异步操作

            /*****查询*****/
            var filter = Builders<BsonDocument>.Filter.Eq("student_id", 10000);
            var studentDocument = collection.Find(filter).FirstOrDefault();
            Console.WriteLine(studentDocument.ToString());
            var documents = collection.Find(new BsonDocument()).ToList();
            foreach (BsonDocument doc in documents)
            {
                Console.WriteLine(doc.ToString());
            }
            //条件查询
            var highExamScoreFilter = Builders<BsonDocument>.Filter.ElemMatch<BsonValue>(
"scores", new BsonDocument { { "type", "exam" },
{ "score", new BsonDocument { { "$gte", 95 } } }
});
            var highExamScores = collection.Find(highExamScoreFilter).ToList();
            //数据量比较大
            var cursor = collection.Find(highExamScoreFilter).ToCursor();
            foreach (var doc in cursor.ToEnumerable())
            {
                Console.WriteLine(doc);
            }
            //或者
            //await collection.Find(highExamScoreFilter)
            //.ForEachAsync(document => Console.WriteLine(document));
            //结果排序
            var sort = Builders<BsonDocument>.Sort.Descending("student_id");
            var highestScores = collection.Find(highExamScoreFilter).Sort(sort);

            /*****更新*****/
            var filterId = Builders<BsonDocument>.Filter.Eq("student_id", 10000);
            var update = Builders<BsonDocument>.Update.Set("class_id", 483);
            collection.UpdateOne(filterId, update);
            //更新数组中数据
            var arrayFilter = Builders<BsonDocument>.Filter.Eq("student_id", 10000)
     & Builders<BsonDocument>.Filter.Eq("scores.type", "exam");
            var arrayUpdate = Builders<BsonDocument>.Update.Set("scores.$.score", 100);
            collection.UpdateOne(arrayFilter, arrayUpdate);

            /*****删除*****/
            var deleteFilter = Builders<BsonDocument>.Filter.Eq("student_id", 10000);
            collection.DeleteOne(deleteFilter);
            //删除多条
            var deleteLowExamFilter = Builders<BsonDocument>.Filter.ElemMatch<BsonValue>("scores",
     new BsonDocument { { "type", "exam" }, {"score", new BsonDocument { { "$lt", 60 }}}
});
            collection.DeleteMany(deleteLowExamFilter);

        }
    }
}       

推荐文档