天天看點

MongoDB via Dotnet Core資料映射詳解

用好資料映射,MongoDB via Dotnet Core開發變會成一件超級快樂的事。

一、前言

MongoDB這幾年已經成為NoSQL的頭部資料庫。

由于MongoDB free schema的特性,使得它在網際網路應用方面優于正常資料庫,成為了相當一部分大廠的主資料選擇;而它的快速布署和開發簡單的特點,也吸引着大量小開發團隊的支援。

關于MongoDB快速布署,我在15分鐘從零開始搭建支援10w+使用者的生産環境(二)裡有寫,需要了可以去看看。

作為一個資料庫,基本的操作就是CRUD。MongoDB的CRUD,不使用SQL來寫,而是提供了更簡單的方式。

方式一、BsonDocument方式

BsonDocument方式,适合能熟練使用MongoDB Shell的開發者。MongoDB Driver提供了完全覆寫Shell指令的各種方式,來處理使用者的CRUD操作。

這種方法自由度很高,可以在不需要知道完整資料集結構的情況下,完成資料庫的CRUD操作。

方式二、資料映射方式

資料映射是最常用的一種方式。準備好需要處理的資料類,直接把資料類映射到MongoDB,并對資料集進行CRUD操作。

下面,對資料映射的各個部分,我會逐個說明。

    為了防止不提供原網址的轉載,特在這裡加上原文連結:https://www.cnblogs.com/tiger-wang/p/13185605.html

二、開發環境&基礎工程

這個Demo的開發環境是:Mac + VS Code + Dotnet Core 3.1.2。

建立工程:

% dotnet new sln -o demo
The template "Solution File" was created successfully.
% cd demo 
% dotnet new console -o demo
The template "Console Application" was created successfully.

Processing post-creation actions...
Running 'dotnet restore' on demo/demo.csproj...
  Determining projects to restore...
  Restored demo/demo/demo.csproj (in 162 ms).

Restore succeeded.
% dotnet sln add demo/demo.csproj 
Project `demo/demo.csproj` added to the solution.
           

建立工程完成。

下面,增加包

mongodb.driver

到工程:

% cd demo
% dotnet add package mongodb.driver
  Determining projects to restore...
info : Adding PackageReference for package 'mongodb.driver' into project 'demo/demo/demo.csproj'.
info : Committing restore...
info : Writing assets file to disk. Path: demo/demo/obj/project.assets.json
log  : Restored /demo/demo/demo.csproj (in 6.01 sec).
           

項目準備完成。

看一下目錄結構:

% tree .
.
├── demo
│   ├── Program.cs
│   ├── demo.csproj
│   └── obj
│       ├── demo.csproj.nuget.dgspec.json
│       ├── demo.csproj.nuget.g.props
│       ├── demo.csproj.nuget.g.targets
│       ├── project.assets.json
│       └── project.nuget.cache
└── demo.sln
           

mongodb.driver

是MongoDB官方的資料庫SDK,從Nuget上安裝即可。

三、Demo準備工作

建立資料映射的模型類

CollectionModel.cs

,現在是個空類,後面所有的資料映射相關内容會在這個類進行說明:

public class CollectionModel
{
}
           

并修改

Program.cs

,準備

Demo

方法,以及連接配接資料庫:

class Program
{
    private const string MongoDBConnection = "mongodb://localhost:27031/admin";

    private static IMongoClient _client = new MongoClient(MongoDBConnection);
    private static IMongoDatabase _database = _client.GetDatabase("Test");
    private static IMongoCollection<CollectionModel> _collection = _database.GetCollection<CollectionModel>("TestCollection");

    static async Task Main(string[] args)
    {
        await Demo();
        Console.ReadKey();
    }

    private static async Task Demo()
    {
    }
}
           

四、字段映射

從上面的代碼中,我們看到,在生成

Collection

對象時,用到了

CollectionModel

IMongoDatabase _database = _client.GetDatabase("Test");
IMongoCollection<CollectionModel> _collection = _database.GetCollection<CollectionModel>("TestCollection");
           

這兩行,其實就完成了一個映射的工作:把

MongoDB

中,

Test

資料庫下,

TestCollection

資料集(就是SQL中的資料表),映射到

CollectionModel

這個資料類中。換句話說,就是用

CollectionModel

這個類,來完成對資料集

TestCollection

的所有操作。

保持

CollectionModel

為空,我們往資料庫寫入一行資料:

private static async Task Demo()
{
    CollectionModel new_item = new CollectionModel();
    await _collection.InsertOneAsync(new_item);
}
           

執行,看一下寫入的資料:

{ 
    "_id" : ObjectId("5ef1d8325327fd4340425ac9")
}
           

OK,我們已經寫進去一條資料了。因為映射類是空的,是以寫入的資料,也隻有

_id

一行内容。

但是,為什麼會有一個

_id

呢?

1. ID字段

MongoDB資料集中存放的資料,稱之為文檔(

Document

)。每個文檔在存放時,都需要有一個ID,而這個ID的名稱,固定叫

_id

當我們建立映射時,如果給出

_id

字段,則MongoDB會采用這個ID做為這個文檔的ID,如果不給出,MongoDB會自動添加一個

_id

字段。

例如:

public class CollectionModel
{
    public ObjectId _id { get; set; }
    public string title { get; set; }
    public string content { get; set; }
}
           

public class CollectionModel
{
    public string title { get; set; }
    public string content { get; set; }
}
           

在使用上是完全一樣的。唯一的差別是,如果映射類中不寫

_id

,則MongoDB自動添加

_id

時,會用

ObjectId

作為這個字段的資料類型。

ObjectId

是一個全局唯一的資料。

當然,MongoDB允許使用其它類型的資料作為ID,例如:

string

int

long

GUID

等,但這就需要你自己去保證這些資料不超限并且唯一。

例如,我們可以寫成:

public class CollectionModel
{
    public long _id { get; set; }
    public string title { get; set; }
    public string content { get; set; }
}
           

我們也可以在類中修改

_id

名稱為别的内容,但需要加一個描述屬性

BsonId

public class CollectionModel
{
    [BsonId]
    public ObjectId topic_id { get; set; }
    public string title { get; set; }
    public string content { get; set; }
}
           

這兒特别要注意:

BsonId

屬性會告訴映射,

topic_id

就是這個文檔資料的ID。MongoDB在儲存時,會将這個

topic_id

轉成

_id

儲存到資料集中。

在MongoDB資料集中,ID字段的名稱固定叫

_id

。為了代碼的閱讀友善,可以在類中改為别的名稱,但這不會影響MongoDB中存放的ID名稱。

修改Demo代碼:

private static async Task Demo()
{
    CollectionModel new_item = new CollectionModel()
    {
        title = "Demo",
        content = "Demo content",
    };
    await _collection.InsertOneAsync(new_item);
}
           

跑一下Demo,看看儲存的結果:

{ 
    "_id" : ObjectId("5ef1e1b1bc1e18086afe3183"), 
    "title" : "Demo", 
    "content" : "Demo content"
}
           

2. 簡單字段

就是正常的資料字段,直接寫就成。

public class CollectionModel
{
    [BsonId]
    public ObjectId topic_id { get; set; }
    public string title { get; set; }
    public string content { get; set; }
    public int favor { get; set; }
}
           

儲存後的資料:

{ 
    "_id" : ObjectId("5ef1e9caa9d16208de2962bb"), 
    "title" : "Demo", 
    "content" : "Demo content", 
    "favor" : NumberInt(100)
}
           

3. 一個的特殊的類型 - Decimal

說Decimal特殊,是因為MongoDB在早期,是不支援Decimal的。直到MongoDB v3.4開始,資料庫才正式支援Decimal。

是以,如果使用的是v3.4以後的版本,可以直接使用,而如果是以前的版本,需要用以下的方式:

[BsonRepresentation(BsonType.Double, AllowTruncation = true)]
public decimal price { get; set; }
           

其實就是把Decimal通過映射,轉為Double存儲。

4. 類字段

把類作為一個資料集的一個字段。這是MongoDB作為文檔NoSQL資料庫的特色。這樣可以很友善的把相關的資料組織到一條記錄中,友善展示時的查詢。

我們在項目中添加兩個類

Contact

Author

public class Contact
{
    public string mobile { get; set; }
}
           
public class Author
{
    public string name { get; set; }
    public List<Contact> contacts { get; set; }
}
           

然後,把

Author

加到

CollectionModel

中:

public class CollectionModel
{
    [BsonId]
    public ObjectId topic_id { get; set; }
    public string title { get; set; }
    public string content { get; set; }
    public int favor { get; set; }
    public Author author { get; set; }
}
           

嗯,開始變得有點複雜了。

完善Demo代碼:

private static async Task Demo()
{
    CollectionModel new_item = new CollectionModel()
    {
        title = "Demo",
        content = "Demo content",
        favor = 100,
        author = new Author
        {
            name = "WangPlus",
            contacts = new List<Contact>(),
        }
    };

    Contact contact_item1 = new Contact()
    {
        mobile = "13800000000",
    };
    Contact contact_item2 = new Contact()
    {
        mobile = "13811111111",
    };
    new_item.author.contacts.Add(contact_item1);
    new_item.author.contacts.Add(contact_item2);

    await _collection.InsertOneAsync(new_item);
}
           

儲存的資料是這樣的:

{ 
    "_id" : ObjectId("5ef1e635ce129908a22dfb5e"), 
    "title" : "Demo", 
    "content" : "Demo content", 
    "favor" : NumberInt(100),
    "author" : {
        "name" : "WangPlus", 
        "contacts" : [
            {
                "mobile" : "13800000000"
            }, 
            {
                "mobile" : "13811111111"
            }
        ]
    }
}
           

這樣的資料結構,用着不要太爽!

5. 枚舉字段

枚舉字段在使用時,跟類字段相似。

建立一個枚舉

TagEnumeration

public enum TagEnumeration
{
    CSharp = 1,
    Python = 2,
}
           

CollectionModel

public class CollectionModel
{
    [BsonId]
    public ObjectId topic_id { get; set; }
    public string title { get; set; }
    public string content { get; set; }
    public int favor { get; set; }
    public Author author { get; set; }
    public TagEnumeration tag { get; set; }
}
           
private static async Task Demo()
{
    CollectionModel new_item = new CollectionModel()
    {
        title = "Demo",
        content = "Demo content",
        favor = 100,
        author = new Author
        {
            name = "WangPlus",
            contacts = new List<Contact>(),
        },
        tag = TagEnumeration.CSharp,
    };
    /* 後邊代碼略過 */
}
           

運作後看資料:

{ 
    "_id" : ObjectId("5ef1eb87cbb6b109031fcc31"), 
    "title" : "Demo", 
    "content" : "Demo content", 
    "favor" : NumberInt(100), 
    "author" : {
        "name" : "WangPlus", 
        "contacts" : [
            {
                "mobile" : "13800000000"
            }, 
            {
                "mobile" : "13811111111"
            }
        ]
    }, 
    "tag" : NumberInt(1)
}
           

在這裡,

tag

儲存了枚舉的值。

我們也可以儲存枚舉的字元串。隻要在

CollectionModel

tag

聲明上加個屬性:

public class CollectionModel
{
    [BsonId]
    public ObjectId topic_id { get; set; }
    public string title { get; set; }
    public string content { get; set; }
    public int favor { get; set; }
    public Author author { get; set; }
    [BsonRepresentation(BsonType.String)]
    public TagEnumeration tag { get; set; }
}
           

資料會變成:

{ 
    "_id" : ObjectId("5ef1ec448f1d540919d15904"), 
    "title" : "Demo", 
    "content" : "Demo content", 
    "favor" : NumberInt(100), 
    "author" : {
        "name" : "WangPlus", 
        "contacts" : [
            {
                "mobile" : "13800000000"
            }, 
            {
                "mobile" : "13811111111"
            }
        ]
    }, 
    "tag" : "CSharp"
}
           

6. 日期字段

日期字段會稍微有點坑。

這個坑其實并不源于MongoDB,而是源于C#的

DateTime

類。我們知道,時間根據時區不同,時間也不同。而

DateTime

并不準确描述時區的時間。

我們先在

CollectionModel

中增加一個時間字段:

public class CollectionModel
{
    [BsonId]
    public ObjectId topic_id { get; set; }
    public string title { get; set; }
    public string content { get; set; }
    public int favor { get; set; }
    public Author author { get; set; }
    [BsonRepresentation(BsonType.String)]
    public TagEnumeration tag { get; set; }
    public DateTime post_time { get; set; }
}
           

修改Demo:

private static async Task Demo()
{
    CollectionModel new_item = new CollectionModel()
    {
        /* 前邊代碼略過 */
        post_time = DateTime.Now, /* 2020-06-23T20:12:40.463+0000 */
    };
    /* 後邊代碼略過 */
}
           

運作看資料:

{ 
    "_id" : ObjectId("5ef1f1b9a75023095e995d9f"), 
    "title" : "Demo", 
    "content" : "Demo content", 
    "favor" : NumberInt(100), 
    "author" : {
        "name" : "WangPlus", 
        "contacts" : [
            {
                "mobile" : "13800000000"
            }, 
            {
                "mobile" : "13811111111"
            }
        ]
    }, 
    "tag" : "CSharp", 
    "post_time" : ISODate("2020-06-23T12:12:40.463+0000")
}
           

對比代碼時間和資料時間,會發現這兩個時間差了8小時 - 正好的中國的時區時間。

MongoDB規定,在資料集中存儲時間時,隻會儲存UTC時間。

如果隻是儲存(像上邊這樣),或者查詢時使用時間作為條件(例如查詢

post_time < DateTime.Now

的資料)時,是可以使用的,不會出現問題。

但是,如果是查詢結果中有時間字段,那這個字段,會被

DateTime

預設設定為

DateTimeKind.Unspecified

類型。而這個類型,是無時區資訊的,輸出顯示時,會造成混亂。

為了避免這種情況,在進行時間字段的映射時,需要加上屬性:

[BsonDateTimeOptions(Kind = DateTimeKind.Local)]
public DateTime post_time { get; set; }
           

這樣做,會強制

DateTime

類型的字段為

DateTimeKind.Local

類型。這時候,從顯示到使用就正确了。

但是,别高興的太早,這兒還有一個但是。

這個但是是這樣的:資料集中存放的是UTC時間,跟我們正常的時間有8小時時差,如果我們需要按日統計,比方每天的銷售額/點選量,怎麼搞?上面的方式,解決不了。

當然,基于MongoDB自由的字段處理,可以把需要統計的字段,按年月日時分秒拆開存放,像下面這樣的:

class Post_Time
{
    public int year { get; set; }
    public int month { get; set; }
    public int day { get; set; }
    public int hour { get; set; }
    public int minute { get; set; }
    public int second { get; set; }
}
           

能解決,但是Low哭了有沒有?

下面,終極方案來了。它就是:改寫MongoDB中對于

DateTime

字段的序列化類。當當當~~~

先建立一個類

MyDateTimeSerializer

public class MyDateTimeSerializer : DateTimeSerializer
{
    public override DateTime Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
    {
        var obj = base.Deserialize(context, args);
        return new DateTime(obj.Ticks, DateTimeKind.Unspecified);
    }
    public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, DateTime value)
    {
        var utcValue = new DateTime(value.Ticks, DateTimeKind.Utc);
        base.Serialize(context, args, utcValue);
    }
}
           

代碼簡單,一看就懂。

注意,使用這個方法,上邊那個對于時間加的屬性

[BsonDateTimeOptions(Kind = DateTimeKind.Local)]

一定不要添加,要不然就等着哭吧:P

建立完了,怎麼用?

如果你隻想對某個特定映射的特定字段使用,比方隻對

CollectionModel

post_time

字段來使用,可以這麼寫:

[BsonSerializer(typeof(MyDateTimeSerializer))]
public DateTime post_time { get; set; }
           

或者全局使用:

BsonSerializer.RegisterSerializer(typeof(DateTime), new MongoDBDateTimeSerializer());
           

BsonSerializer

是MongoDB.Driver的全局對象。是以這個代碼,可以放到使用資料庫前的任何地方。例如在Demo中,我放在

Main

裡了:

static async Task Main(string[] args)
{
    BsonSerializer.RegisterSerializer(typeof(DateTime), new MyDateTimeSerializer());

    await Demo();
    Console.ReadKey();
}
           

這回看資料,資料集中的

post_time

跟目前時間顯示完全一樣了,你統計,你分組,可以随便霍霍了。

7. Dictionary字段

這個需求很奇怪。我們希望在一個Key-Value的文檔中,儲存一個Key-Value的資料。但這個需求又是真實存在的,比方儲存一個使用者的标簽和标簽對應的命中次數。

資料聲明很簡單:

public Dictionary<string, int> extra_info { get; set; }
           

MongoDB定義了三種儲存屬性:

Document

ArrayOfDocuments

ArrayOfArrays

,預設是

Document

屬性寫法是這樣的:

[BsonDictionaryOptions(DictionaryRepresentation.ArrayOfDocuments)]
public Dictionary<string, int> extra_info { get; set; }
           

這三種屬性下,儲存在資料集中的資料結構有差別。

DictionaryRepresentation.Document

{ 
    "extra_info" : {
        "type" : NumberInt(1), 
        "mode" : NumberInt(2)
    }
}
           

DictionaryRepresentation.ArrayOfDocuments

{ 
    "extra_info" : [
        {
            "k" : "type", 
            "v" : NumberInt(1)
        }, 
        {
            "k" : "mode", 
            "v" : NumberInt(2)
        }
    ]
}
           

DictionaryRepresentation.ArrayOfArrays

{ 
    "extra_info" : [
        [
            "type", 
            NumberInt(1)
        ], 
        [
            "mode", 
            NumberInt(2)
        ]
    ]
}
           

這三種方式,從資料儲存上并沒有什麼差別,但從查詢來講,如果這個字段需要進行查詢,那三種方式差別很大。

如果采用BsonDocument方式查詢,

DictionaryRepresentation.Document

無疑是寫着最友善的。

如果用Builder方式查詢,

DictionaryRepresentation.ArrayOfDocuments

是最容易寫的。

DictionaryRepresentation.ArrayOfArrays

就算了。數組套數組,查詢條件寫死人。

我自己在使用時,多數情況用

DictionaryRepresentation.ArrayOfDocuments

五、其它映射屬性

上一章介紹了資料映射的完整内容。除了這些内容,MongoDB還給出了一些映射屬性,供大家看心情使用。

1. BsonElement屬性

這個屬性是用來改資料集中的字段名稱用的。

看代碼:

[BsonElement("pt")]
public DateTime post_time { get; set; }
           

在不加

BsonElement

的情況下,通過資料映射寫到資料集中的文檔,字段名就是變量名,上面這個例子,字段名就是

post_time

加上

BsonElement

後,資料集中的字段名會變為

pt

2. BsonDefaultValue屬性

看名稱就知道,這是用來設定字段的預設值的。

[BsonDefaultValue("This is a default title")]
public string title { get; set; }
           

當寫入的時候,如果映射中不傳入值,則資料庫會把這個預設值存到資料集中。

3. BsonRepresentation屬性

這個屬性是用來在映射類中的資料類型和資料集中的資料類型做轉換的。

[BsonRepresentation(BsonType.String)]
public int favor { get; set; }
           

這段代表表示,在映射類中,

favor

字段是

int

類型的,而存到資料集中,會儲存為

string

類型。

前邊

Decimal

轉換和枚舉轉換,就是用的這個屬性。

4. BsonIgnore屬性

這個屬性用來忽略某些字段。忽略的意思是:映射類中某些字段,不希望被儲存到資料集中。

[BsonIgnore]
public string ignore_string { get; set; }
           

這樣,在儲存資料時,字段

ignore_string

就不會被儲存到資料集中。

六、總結

資料映射本身沒什麼新鮮的内容,但在MongoDB中,如果用好了映射,開發過程從效率到爽的程度,都不是SQL可以相比的。正所謂:

一入Mongo深似海,從此SQL是路人。

謝謝大家!

(全文完)

本文的配套代碼在https://github.com/humornif/Demo-Code/tree/master/0015/demo

MongoDB via Dotnet Core資料映射詳解

微信公衆号:老王Plus

掃描二維碼,關注個人公衆号,可以第一時間得到最新的個人文章和内容推送

本文版權歸作者所有,轉載請保留此聲明和原文連結