C#使用MongoDB-第一章 基本操作

这里在C#中所使用的连接MongoDB数据库的依赖库为MongoDB.Driver,使用前先到Nuget中进行安装。
在这里插入图片描述

连接MongoDB

MongoDB.Driver中,用于连接数据库的类型为MongoClient

  • 注意,MongoClient对象表示的是数据库的连接池,因此我们在开发项目时,大多数情况只需要创建一个MongoClient实例就够了。

一、连接单机服务

标准的连接字符串:mongodb://username:password@host[:port]/defaultauthdb?

  • username:password@:用户名与密码,如果服务开启了用户认证,那么可以在连接字符串中写入,否则可以不写。
  • host[:port]:要连接的服务的主机名(或IP地址)和端口,端口可以不写,默认为27017
  • /defaultauthdb:创建登录用户时所用的数据库,登录时会到该数据库中进行用户认证。如果连接字符串中没有写明username:password@,此段可以不写,如果连接字符串中写明了username:password@但是没有写明数据库,那么将会到admin数据库中进行用户认证。
  • ?:连接选项,一般不写直接用默认的就可以了。
const string conStr= "mongodb://moo:[email protected]:27017/FirstMongo";
var client = new MongoClient(conStr);
var studentCollection = client.GetDatabase("FirstMongo").GetCollection<Student>("Student");

二、连接副本集

要连接集群,需要指定集群的其中一台主机或多台主机的主机名(或IP地址)以及端口号,并将选项replicaSet设置为集群名字。

集群的连接字符串:mongodb://moo:[email protected]:27017/FirstMongo?replicaSet=myrs

const string conStr = "mongodb://moo:[email protected]:27017/FirstMongo?replicaSet=myrs";
var client = new MongoClient(conStr);
var studentCollection = client.GetDatabase("FirstMongo").GetCollection<Student>("Student");

三、连接分片

连接分片时跟连接单机差不多,主要是指定Mongos(分片的路由服务)的主机名和端口号,如果同一个主机上有多个路由服务,那么可以写成host:port1,port2,…,如果多个路由服务都在不同主机上,那么可以写成host1:port1,host2:port2,…

分片的连接字符串:mongodb://moo:[email protected]:27017,27018/FirstMongo

const string conStr = "mongodb://moo:[email protected]:27017,27018/FirstMongo";
var client = new MongoClient(conStr);
var studentCollection = client.GetDatabase("FirstMongo").GetCollection<Student>("Student");

数据写入

  • 实体类

    class Student
    {
        public ObjectId Id { get; set; }
        public string? Name { get; set; }
        [BsonDefaultValue(23)]
        public int Age { get; set; }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime Time { get; set; } = DateTime.Now;
    }
    

一、插入文档

1、插入单个文档

InsertOneAsync(document):异步插入单条数据。

InsertOne(document):同步插入单条数据。

  • 示例

    const string conStr = "mongodb://moo:[email protected]:27017,27018/FirstMongo";
    var client = new MongoClient(conStr);
    IMongoCollection<Student> studentCollection = client.GetDatabase("FirstMongo").GetCollection<Student>("Student");
    studentCollection.InsertOne(new Student { Name = "Test" ,Age = 23 });
    

2、插入多个文档

InsertManyAsync(IEnumerable documents):异步插入多条数据。

InsertMany(IEnumerable documents):同步插入多条数据。

  • 示例

    const string conStr = "mongodb://moo:[email protected]:27017,27018/FirstMongo";
    var client = new MongoClient(conStr);
    IMongoCollection<Student> studentCollection = client.GetDatabase("FirstMongo").GetCollection<Student>("Student");
    studentCollection.InsertMany(new List<Student>()
    {
        new Student
        {
            Age = 22,
            Name   = "ssssss1",
        },
        new Student
        {
            Age = 24,
            Name   = "ssssss2",
        },
        new Student
        {   Age = 23,
            Name   = "ssssss3"
        }
    });
    

二、修改文档

1、修改单个文档

修改单个文档,默认会修改第一个匹配条件的文档。

Task UpdateOneAsync(FilterDefinition filter, UpdateDefinition update[, ReplaceOptions options]):异步修改指定条件的文档。

UpdateResult UpdateOne(FilterDefinition filter, UpdateDefinition update[, ReplaceOptions options]):同步修改指定条件的文档。

  • filter:条件过滤器,可以通过Builders.Filter实例的方法来创建,支持多种方法包括where方法。此参数可以用lambda表达式代替

  • update:更新内容,可以通过Builders.Update.Set()方法来创建。

  • options:更换操作的设置选项,其中有几个较为常用选项:new ReplaceOptions() {IsUpsert=true, Hint="Name"}

    • IsUpsert:表示如果匹配不到合适的,是否插入新文档。
    • Hint:设置或者获取执行操作时搜索文档所用的索引。
  • UpdateResult:返回结果,其中保存了修改的条数、修改文档的_id等数据。

  • 示例

    const string conStr = "mongodb://moo:[email protected]:27017,27018/FirstMongo";
    var client = new MongoClient(conStr);
    IMongoCollection<Student> studentCollection = client.GetDatabase("FirstMongo").GetCollection<Student>("Student");
    var filter = Builders<Student>.Filter.Where(s => s.Age == 23);
    var update = Builders<Student>.Update.Set(s => s.Age, 40);
    var result = studentCollection.UpdateOne(filter,update);
    

2、修改多个文档

修改多个文档,会将所有符合条件的文档都进行修改

Task UpdateManyAsync(FilterDefinition filter, UpdateDefinition update[, ReplaceOptions options]):异步修改多个文档。

UpdateResult UpdateMany(FilterDefinition filter, UpdateDefinition update[, ReplaceOptions options]):同步修改多个文档。

使用方式个修改一个文档是一样的,这里就不举例了。

三、替换文档

Task ReplaceOneAsync(FilterDefinition filter, TDocument replacement[, ReplaceOptions options]):异步替换指定文档。

ReplaceOneResult ReplaceOne(FilterDefinition filter, TDocument replacement[, ReplaceOptions options]):同步替换指定文档。

  • filter:条件过滤器,可以通过Builders.Filter实例的方法来创建,支持多种方法包括where方法。此参数可以用lambda表达式代替
  • replacement:要拿来替换的对象。
  • options:更换操作的设置选项,其中有几个较为常用选项:new ReplaceOptions() {IsUpsert=true, Hint="Name"}
    • IsUpsert:表示如果匹配不到合适的,是否插入新文档。
    • Hint:设置或者获取执行操作时搜索文档所用的索引。
  • ReplaceOneResult:替换结果。

注意,这个替换操作,我用了一下,如果替换时我不给新文档的实体类设置Id,会报错,要设置Id属性,并且要设置跟更新的那条文档的Id相同才不会报错,不知道为啥。

  • 示例

    const string conStr = "mongodb://moo:[email protected]:27017,27018/FirstMongo";
    var client = new MongoClient(conStr);
    IMongoCollection<Student> studentCollection = client.GetDatabase("FirstMongo").GetCollection<Student>("Student");
    var filter = Builders<Student>.Filter.Eq(s => s.Age,24);
    var s = new Student { 
        Name = "replace", 
        Age = 50 
    };
    var temp = studentCollection.Find(filter).First();
    s.Id = temp.Id;
    var result = studentCollection.ReplaceOne(filter, s, new ReplaceOptions() {  IsUpsert=true });
    

三、删除

1、删除单个文档

Task DeleteOneAsync(FilterDefinition filter [, DeleteOptions options]):异步删除单个指定文档。

DeleteResult DeleteOne(FilterDefinition filter [, DeleteOptions options]):同步删除单个指定文档

  • filter:条件过滤器,可以通过Builders.Filter实例的方法来创建,支持多种方法包括where方法。此参数可以用lambda表达式代替

  • options:删除操作的设置选项,其中有个较为常用选项:new ReplaceOptions() {Hint="Name"}

    • Hint:设置或者获取执行操作时搜索文档所用的索引。
  • DeleteResult:删除后的返回结果,

  • 示例

    const string conStr = "mongodb://moo:[email protected]:27017,27018/FirstMongo";
    var client = new MongoClient(conStr);
    IMongoCollection<Student> studentCollection = client.GetDatabase("FirstMongo").GetCollection<Student>("Student");
    var filter = Builders<Student>.Filter.Eq(s => s.Age,24);
    var result = studentCollection.DeleteOne(filter);
    //也支持直接传入lambda表达式
    // var result = studentCollection.DeleteOne(s=>s.Age == 24 );
    

2、删除多个文档

Task DeleteManyAsync(FilterDefinition filter [, DeleteOptions options]):异步删除多个符合条件的文档。

Task DeleteMany(FilterDefinition filter [, DeleteOptions options]):同步删除多个符合条件的文档。

用法跟删除单个文档是一样的,这里就不举例了。

数据读取

  • 实体类

    class Student
    {
        public ObjectId Id { get; set; }
        public string? Name { get; set; }
        [BsonDefaultValue(23)]
        public int Age { get; set; }
        [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
        public DateTime Time { get; set; } = DateTime.Now;
    }
    

一、查询文档

1、查询单个文档

Task collectionObj.Find(FilterDefinition filter[,FindOptions options]).FirstOrDefault():异步查询符合条件的第一个文档,无匹配文档则返回null

TDocument collectionObj.Find(FilterDefinition filter[,FindOptions options]).FirstOrDefault():同步查询符合条件的第一个文档,无匹配文档则返回null

  • 这里的collectionObj指的是从驱动库获取的集合对象。

  • TDocument:返回结果,与获取集合对象时的泛型参数类型有关。(可以参考一下下面的例子)

  • filter:条件过滤器,可以通过Builders.Filter实例的方法来创建,支持多种方法包括where方法。此参数可以用lambda表达式代替

  • options:查询操作的设置选项,其中有个较为常用选项:new ReplaceOptions() {Hint="Name", MaxTime=100}

    • Hint:设置或者获取执行操作时搜索文档所用的索引。
    • MaxTime:本次操作的最长执行时间,为TimeSpan类型。
  • 示例

    const string conStr = "mongodb://moo:[email protected]:27017,27018/FirstMongo";
    var client = new MongoClient(conStr);
    IMongoCollection<Student> studentCollection = client.GetDatabase("FirstMongo").GetCollection<Student>("Student");
    var student = studentCollection.Find(s => s.Age == 22,new FindOptions {MaxTime = TimeSpan.FromMilliseconds(20) }).ToList();
    

2、查询多个文档

Task> collectionObj.Find(FilterDefinition filter[,FindOptions options]).ToListAsync():异步查询符合条件的所有文档。

List collectionObj.Find(FilterDefinition filter[,FindOptions options]).ToList():同步查询符合条件的所有文档。

用法跟查询单个是一样的,这里就不举例了。

3、查询所有文档

想要查询所有文档,直接将空过滤器Builders.Filter.Empty传入Find即可。

const string conStr = "mongodb://moo:[email protected]:27017,27018/FirstMongo";
var client = new MongoClient(conStr);
IMongoCollection<Student> studentCollection = client.GetDatabase("FirstMongo").GetCollection<Student>("Student");
var student = studentCollection.Find(Builders<Guitar>.Filter.Empty).ToList();

二、常用的过滤器

1、All()、Size()

All():如果文档中的指定数组字段包含传入的所有元素,则匹配。

Size():如果文档中的指定数组字段的元素个数与指定个数相等,则匹配。

var filter1 = Builders<Student>.Filter.All(s => s.Datas, new List<string> {"a","b","c"});
var filter2 = Builders<Student>.Filter.Size(s => s.Datas, 3);

2、Exists()

Exists():存在指定的字段则匹配。

var filter = Builders<Student>.Filter.Exists(s => s.Class);

3、Regex()

Regex():正则匹配

var filter = Builders<Student>.Filter.Regex(g => g.Name, "^S");

三、Linq语句的配合使用(推荐使用)

MongoDB.Driver驱动库支持使用Linq语句,当我们使用Linq语句进行查询请求时,驱动库会自动将其转换成对应的聚合操作。
要使用Linq,只需要调用集合对象AsQueryable()方法,获得对应的IMongoQueryable实例,就可以尽情的Linq了

const string conStr = "mongodb://moo:[email protected]:27017,27018/FirstMongo";
var client = new MongoClient(conStr);
IMongoCollection<Student> studentCollection = client.GetDatabase("FirstMongo").GetCollection<Student>("Student");
var queryableCollection = studentCollection.AsQueryable();
var result = queryableCollection.Take(3).Where(s => s.Age > 3).ToList();

驱动库所支持的Linq方法,基本上能满足绝大部分的查询了

Method Name Description
Any Determines if any documents match the specified criteria
Average Calculates the average of the specified fields
Count Returns an Int32 that represents the number of documents that match the specified criteria
LongCount Returns an Int64 that represents the number of documents that match the specified criteria
Distinct Returns distinct documents that match the specified criteria
First Returns the first matching document, and throws an exception if none are found
FirstOrDefault Returns the first matching document, or null if none are found
GroupBy Groups documents based on specified criteria
GroupJoin Performs a left outer join to another collection in the same database
Max Returns the document with the maximum specified value
OfType Returns documents that match the specified of type
OrderBy, OrderByDescending Returns results in a specified sort order
ThenBy, ThenByDescending Allows a secondary sort to be specified
Select Selects documents based on specified criteria
SelectMany Projects each element of a sequence and combines the resulting sequences into one document
Single Returns the only matching document, and throws an exception if there is not exactly one document
SingleOrDefault Returns a single matching document or null if no documents match
Skip Skips over a specified number of documents and returns the rest of the results
Sum Returns the sum of the values in a specified field
Take Specifies the number of results to return
Where Returns all documents that match your specified criteria

你可能感兴趣的:(C#操作数据库,c#,mongodb,开发语言)