国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

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

這篇具有很好參考價值的文章主要介紹了C#使用MongoDB-第一章 基本操作。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點(diǎn)擊"舉報違法"按鈕提交疑問。

這里在C#中所使用的連接MongoDB數(shù)據(jù)庫的依賴庫為MongoDB.Driver,使用前先到Nuget中進(jìn)行安裝。
C#使用MongoDB-第一章 基本操作,C#操作數(shù)據(jù)庫,c#,mongodb,開發(fā)語言

連接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了

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)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請點(diǎn)擊違法舉報進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • 分布式數(shù)據(jù)庫NoSQL(二)——MongoDB 數(shù)據(jù)庫基本操作

    分布式數(shù)據(jù)庫NoSQL(二)——MongoDB 數(shù)據(jù)庫基本操作

    MongoDB 是一個基于分布式文件存儲的數(shù)據(jù)庫。由 C++ 語言編寫。旨在為 WEB 應(yīng)用提供可擴(kuò)展的高性能數(shù)據(jù)存儲解決方案。 MongoDB 是一個介于關(guān)系數(shù)據(jù)庫和非關(guān)系數(shù)據(jù)庫之間的產(chǎn)品,是非關(guān)系數(shù)據(jù)庫當(dāng)中功能最豐富,最像關(guān)系數(shù)據(jù)庫的。它支持的數(shù)據(jù)結(jié)構(gòu)非常松散,是類似 json 的

    2024年02月06日
    瀏覽(33)
  • C# 使用OpenCV基本圖像操作功能

    C# 使用OpenCV基本圖像操作功能

    OpenCV是一個開源的跨平臺計(jì)算機(jī)視覺和機(jī)器學(xué)習(xí)軟件庫,可以運(yùn)行在Linux、Windows、Android和Mac OS操作系統(tǒng)上。C#在上位機(jī)開發(fā)中比較常用,有些項(xiàng)目需要在上位機(jī)上加入一些機(jī)器視覺相關(guān)的功能,在下面簡單介紹了C#中使用OpenCV庫的方法。 在管理NuGet包中,搜索OpenCvSharp4,安裝

    2024年02月15日
    瀏覽(90)
  • Java操作mongodb的基本操作

    Java操作mongodb的基本操作

    目錄 MongoDB的基本操作 新增 方式一: 方式二: 刪除: ?帶條件的刪除 修改 修改條件 修改并添加 ?多條件修改: 查詢 普通查詢 條件查詢 ?編輯 多條件查詢 模糊查詢: 查詢除來的結(jié)果有兩種的顯示方式: MongoDB中的文檔本質(zhì)上是一種類似JSON的BSON格式的數(shù)據(jù)。 BSON是一種類

    2023年04月09日
    瀏覽(26)
  • webrtc 入門第一章 基本設(shè)備操作

    webrtc 入門第一章 基本設(shè)備操作

    一、介紹 1、webrtc是什么 webrtc是一個由google發(fā)起的開源實(shí)時通信方案,其中包括視頻/音頻采集、編解碼、數(shù)據(jù)傳輸、音視頻展示的功能。在瀏覽器,桌面應(yīng)用,移動設(shè)備或者lot設(shè)備上都有可以運(yùn)行的api接口,均可實(shí)現(xiàn)實(shí)時通信能力。web開發(fā)者可以基于web api開發(fā)基于視頻、音

    2024年02月02日
    瀏覽(12)
  • MongoDB操作基本教程

    v6.0.7 bin目錄下默認(rèn)可執(zhí)行文件說明 mongod 實(shí)例,這樣不僅減少資源競爭,而且服務(wù)器故障也不會同時影響到多個服務(wù)。 mongos 在分片集群中扮演路由的角色,提供客戶端和分片之間的接口。 mongosh 是 MongoDB 集成的交互式 shell 工具。 數(shù)據(jù)庫工具 需要另外下載:https://www.mongodb

    2024年02月16日
    瀏覽(23)
  • Redis,MongoDB基本操作練習(xí)題

    語法不會可以在官網(wǎng)上查詢MongoDB教程 String類型基本操作: List類型基本操作: hash類型基本操作: 創(chuàng)建一個數(shù)據(jù)庫 名字grade: 創(chuàng)建class集合: 集合中插入若干數(shù)據(jù): 查看班級所有人信息: 查看班級中年齡為8歲的學(xué)生信息: 查看年齡大于10歲的學(xué)生信息: 查看年齡在 4—8歲

    2024年02月16日
    瀏覽(33)
  • MySQL-Redis數(shù)據(jù)類型操作和MongoDB基本操作

    (1) 設(shè)置鍵值: (2) 讀取鍵值: (3) 數(shù)值類型自增1: (4) 數(shù)值類型自減1: (5) 查看值的長度: (1)對列表city插入元素:Shanghai Suzhou Hangzhou (2)將列表city里的頭部的元素移除 (3)將name列表的尾部元素移除到number列表的頭部 (4) 對一個已存在的列表插入新元素

    2024年02月16日
    瀏覽(34)
  • Django Web開發(fā)(day4)——數(shù)據(jù)模型使用與填充網(wǎng)站數(shù)據(jù)(對數(shù)據(jù)庫的基本操作)

    Django Web開發(fā)(day4)——數(shù)據(jù)模型使用與填充網(wǎng)站數(shù)據(jù)(對數(shù)據(jù)庫的基本操作)

    本博客將會涉及:? Django 數(shù)據(jù)模型的使用 視頻數(shù)據(jù)的導(dǎo)入 admin 后臺的使用? 1、Django 數(shù)據(jù)模型的使用? 在上一篇中完成了網(wǎng)站的數(shù)據(jù)模型的創(chuàng)建,在數(shù)據(jù)模型創(chuàng)建之后, Django 會為我們的數(shù)據(jù)模型創(chuàng)建一套數(shù)據(jù)庫抽象的 API 接口,以供我們進(jìn)行檢索數(shù)據(jù)、創(chuàng)建數(shù)據(jù)、更新和修

    2024年01月18日
    瀏覽(36)
  • 第一章 數(shù)據(jù)庫操作

    第一章 數(shù)據(jù)庫操作

    1.1 創(chuàng)建數(shù)據(jù)庫 創(chuàng)建數(shù)據(jù)庫是指在數(shù)據(jù)庫系統(tǒng)中劃分一塊空間,用來存儲相應(yīng)的數(shù)據(jù),這是進(jìn)行表操作的基礎(chǔ),也是數(shù)據(jù)庫管理的基礎(chǔ) 在MySQL中創(chuàng)建數(shù)據(jù)庫之前,可以使用show語句來顯示當(dāng)前已經(jīng)存在的數(shù)據(jù)庫,具體SQL語句如下 創(chuàng)建數(shù)據(jù)庫的SQL語句如下,其中 參數(shù)database_name代

    2024年02月05日
    瀏覽(15)
  • 第一章 數(shù)據(jù)庫的操作

    第一章 數(shù)據(jù)庫的操作

    (1)語法 假設(shè)我們想要創(chuàng)建一個名稱為D1的數(shù)據(jù)庫,可以寫出下圖中的MySQL語句。 (2)字符集與校驗(yàn)規(guī)則 a.定義 字符集顧名思義字符的集合。但 這個字符的集合中不僅包含字符,還包含了每個字符對應(yīng)的數(shù)字編碼 。比如我們在c++和c中常用的字符集:ASCII表。 在了解了字符

    2024年02月16日
    瀏覽(27)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包