這里在C#中所使用的連接MongoDB數(shù)據(jù)庫的依賴庫為MongoDB.Driver
,使用前先到Nuget中進(jìn)行安裝。
連接MongoDB
MongoDB.Driver
中,用于連接數(shù)據(jù)庫的類型為MongoClient
。
- 注意,
MongoClient
對象表示的是數(shù)據(jù)庫的連接池,因此我們在開發(fā)項(xiàng)目時,大多數(shù)情況只需要創(chuàng)建一個MongoClient
實(shí)例就夠了。
一、連接單機(jī)服務(wù)
標(biāo)準(zhǔn)的連接字符串:mongodb://username:password@host[:port]/defaultauthdb?<options>
-
username:password@
:用戶名與密碼,如果服務(wù)開啟了用戶認(rèn)證,那么可以在連接字符串中寫入,否則可以不寫。 -
host[:port]
:要連接的服務(wù)的主機(jī)名(或IP地址)和端口,端口可以不寫,默認(rèn)為27017 -
/defaultauthdb
:創(chuàng)建登錄用戶時所用的數(shù)據(jù)庫,登錄時會到該數(shù)據(jù)庫中進(jìn)行用戶認(rèn)證。如果連接字符串中沒有寫明username:password@
,此段可以不寫,如果連接字符串中寫明了username:password@
但是沒有寫明數(shù)據(jù)庫,那么將會到admin
數(shù)據(jù)庫中進(jìn)行用戶認(rèn)證。 -
?<options>
:連接選項(xiàng),一般不寫直接用默認(rèn)的就可以了。
const string conStr= "mongodb://moo:123456@127.0.0.1:27017/FirstMongo";
var client = new MongoClient(conStr);
var studentCollection = client.GetDatabase("FirstMongo").GetCollection<Student>("Student");
二、連接副本集
要連接集群,需要指定集群的其中一臺主機(jī)或多臺主機(jī)的主機(jī)名(或IP地址)以及端口號,并將選項(xiàng)replicaSet
設(shè)置為集群名字。
集群的連接字符串:mongodb://moo:123456@127.0.0.1:27017/FirstMongo?replicaSet=myrs
const string conStr = "mongodb://moo:123456@127.0.0.1:27017/FirstMongo?replicaSet=myrs";
var client = new MongoClient(conStr);
var studentCollection = client.GetDatabase("FirstMongo").GetCollection<Student>("Student");
三、連接分片
連接分片時跟連接單機(jī)差不多,主要是指定Mongos(分片的路由服務(wù))的主機(jī)名和端口號,如果同一個主機(jī)上有多個路由服務(wù),那么可以寫成host:port1,port2,…
,如果多個路由服務(wù)都在不同主機(jī)上,那么可以寫成host1:port1,host2:port2,…
。
分片的連接字符串:mongodb://moo:123456@127.0.0.1:27017,27018/FirstMongo
const string conStr = "mongodb://moo:123456@127.0.0.1:27017,27018/FirstMongo";
var client = new MongoClient(conStr);
var studentCollection = client.GetDatabase("FirstMongo").GetCollection<Student>("Student");
數(shù)據(jù)寫入
-
實(shí)體類
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)
:異步插入單條數(shù)據(jù)。
InsertOne(document)
:同步插入單條數(shù)據(jù)。
-
示例
const string conStr = "mongodb://moo:123456@127.0.0.1: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<TDocument> documents)
:異步插入多條數(shù)據(jù)。
InsertMany(IEnumerable<TDocument> documents)
:同步插入多條數(shù)據(jù)。
-
示例
const string conStr = "mongodb://moo:123456@127.0.0.1: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、修改單個文檔
修改單個文檔,默認(rèn)會修改第一個匹配條件的文檔。
Task<UpdateResult> UpdateOneAsync(FilterDefinition<TDocument> filter, UpdateDefinition<TDocument> update[, ReplaceOptions options])
:異步修改指定條件的文檔。
UpdateResult UpdateOne(FilterDefinition<TDocument> filter, UpdateDefinition<TDocument> update[, ReplaceOptions options])
:同步修改指定條件的文檔。
-
filter
:條件過濾器,可以通過Builders<Student>.Filter
實(shí)例的方法來創(chuàng)建,支持多種方法包括where
方法。此參數(shù)可以用lambda表達(dá)式代替 -
update
:更新內(nèi)容,可以通過Builders<Student>.Update.Set()
方法來創(chuàng)建。 -
options
:更換操作的設(shè)置選項(xiàng),其中有幾個較為常用選項(xiàng):new ReplaceOptions() {IsUpsert=true, Hint="Name"}
-
IsUpsert
:表示如果匹配不到合適的,是否插入新文檔。 -
Hint
:設(shè)置或者獲取執(zhí)行操作時搜索文檔所用的索引。
-
-
UpdateResult
:返回結(jié)果,其中保存了修改的條數(shù)、修改文檔的_id
等數(shù)據(jù)。 -
示例
const string conStr = "mongodb://moo:123456@127.0.0.1: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、修改多個文檔
修改多個文檔,會將所有符合條件的文檔都進(jìn)行修改
Task<UpdateResult> UpdateManyAsync(FilterDefinition<TDocument> filter, UpdateDefinition<TDocument> update[, ReplaceOptions options])
:異步修改多個文檔。
UpdateResult UpdateMany(FilterDefinition<TDocument> filter, UpdateDefinition<TDocument> update[, ReplaceOptions options])
:同步修改多個文檔。
使用方式個修改一個文檔是一樣的,這里就不舉例了。
三、替換文檔
Task<ReplaceOneResult> ReplaceOneAsync(FilterDefinition<TDocument> filter, TDocument replacement[, ReplaceOptions options])
:異步替換指定文檔。
ReplaceOneResult ReplaceOne(FilterDefinition<TDocument> filter, TDocument replacement[, ReplaceOptions options])
:同步替換指定文檔。
-
filter
:條件過濾器,可以通過Builders<Student>.Filter
實(shí)例的方法來創(chuàng)建,支持多種方法包括where
方法。此參數(shù)可以用lambda表達(dá)式代替 -
replacement
:要拿來替換的對象。 -
options
:更換操作的設(shè)置選項(xiàng),其中有幾個較為常用選項(xiàng):new ReplaceOptions() {IsUpsert=true, Hint="Name"}
-
IsUpsert
:表示如果匹配不到合適的,是否插入新文檔。 -
Hint
:設(shè)置或者獲取執(zhí)行操作時搜索文檔所用的索引。
-
-
ReplaceOneResult
:替換結(jié)果。
注意,這個替換操作,我用了一下,如果替換時我不給新文檔的實(shí)體類設(shè)置Id,會報錯,要設(shè)置Id屬性,并且要設(shè)置跟更新的那條文檔的Id相同才不會報錯,不知道為啥。
-
示例
const string conStr = "mongodb://moo:123456@127.0.0.1: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<DeleteResult> DeleteOneAsync(FilterDefinition<TDocument> filter [, DeleteOptions options])
:異步刪除單個指定文檔。
DeleteResult DeleteOne(FilterDefinition<TDocument> filter [, DeleteOptions options])
:同步刪除單個指定文檔
-
filter
:條件過濾器,可以通過Builders<Student>.Filter
實(shí)例的方法來創(chuàng)建,支持多種方法包括where
方法。此參數(shù)可以用lambda表達(dá)式代替 -
options
:刪除操作的設(shè)置選項(xiàng),其中有個較為常用選項(xiàng):new ReplaceOptions() {Hint="Name"}
-
Hint
:設(shè)置或者獲取執(zhí)行操作時搜索文檔所用的索引。
-
-
DeleteResult
:刪除后的返回結(jié)果, -
示例
const string conStr = "mongodb://moo:123456@127.0.0.1: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表達(dá)式 // var result = studentCollection.DeleteOne(s=>s.Age == 24 );
2、刪除多個文檔
Task<DeleteResult> DeleteManyAsync(FilterDefinition<TDocument> filter [, DeleteOptions options])
:異步刪除多個符合條件的文檔。
Task<DeleteResult> DeleteMany(FilterDefinition<TDocument> filter [, DeleteOptions options])
:同步刪除多個符合條件的文檔。
用法跟刪除單個文檔是一樣的,這里就不舉例了。
數(shù)據(jù)讀取
-
實(shí)體類
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<TDocument> collectionObj.Find(FilterDefinition<TDocument> filter[,FindOptions options]).FirstOrDefault()
:異步查詢符合條件的第一個文檔,無匹配文檔則返回null
。
TDocument collectionObj.Find(FilterDefinition<TDocument> filter[,FindOptions options]).FirstOrDefault()
:同步查詢符合條件的第一個文檔,無匹配文檔則返回null
。
-
這里的
collectionObj
指的是從驅(qū)動庫獲取的集合對象。 -
TDocument
:返回結(jié)果,與獲取集合對象時的泛型參數(shù)類型有關(guān)。(可以參考一下下面的例子) -
filter
:條件過濾器,可以通過Builders<Student>.Filter
實(shí)例的方法來創(chuàng)建,支持多種方法包括where
方法。此參數(shù)可以用lambda表達(dá)式代替 -
options
:查詢操作的設(shè)置選項(xiàng),其中有個較為常用選項(xiàng):new ReplaceOptions() {Hint="Name", MaxTime=100}
-
Hint
:設(shè)置或者獲取執(zhí)行操作時搜索文檔所用的索引。 -
MaxTime
:本次操作的最長執(zhí)行時間,為TimeSpan
類型。
-
-
示例
const string conStr = "mongodb://moo:123456@127.0.0.1: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<List<TDocument>> collectionObj.Find(FilterDefinition<TDocument> filter[,FindOptions options]).ToListAsync()
:異步查詢符合條件的所有文檔。
List<TDocument> collectionObj.Find(FilterDefinition<TDocument> filter[,FindOptions options]).ToList()
:同步查詢符合條件的所有文檔。
用法跟查詢單個是一樣的,這里就不舉例了。
3、查詢所有文檔
想要查詢所有文檔,直接將空過濾器Builders<Guitar>.Filter.Empty
傳入Find
即可。
const string conStr = "mongodb://moo:123456@127.0.0.1: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()
:如果文檔中的指定數(shù)組字段包含傳入的所有元素,則匹配。
Size()
:如果文檔中的指定數(shù)組字段的元素個數(shù)與指定個數(shù)相等,則匹配。
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驅(qū)動庫支持使用Linq語句,當(dāng)我們使用Linq語句進(jìn)行查詢請求時,驅(qū)動庫會自動將其轉(zhuǎn)換成對應(yīng)的聚合操作。
要使用Linq,只需要調(diào)用集合對象AsQueryable()
方法,獲得對應(yīng)的IMongoQueryable<T>
實(shí)例,就可以盡情的Linq了文章來源:http://www.zghlxwxcb.cn/news/detail-799185.html
const string conStr = "mongodb://moo:123456@127.0.0.1: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();
驅(qū)動庫所支持的Linq方法,基本上能滿足絕大部分的查詢了文章來源地址http://www.zghlxwxcb.cn/news/detail-799185.html
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 |
到了這里,關(guān)于C#使用MongoDB-第一章 基本操作的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!