C# 生成 MongoDB 中的 ObjectId
生活随笔
收集整理的這篇文章主要介紹了
C# 生成 MongoDB 中的 ObjectId
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
ObjectId介紹
在MongoDB中,文檔(document)在集合(collection)中的存儲需要一個唯一的_id字段作為主鍵。這個_id默認使用ObjectId來定義,因為ObjectId定義的足夠短小,并盡最大可能的保持唯一性,同時能被快速的生成。
ObjectId?是一個 12 Bytes 的?BSON?類型,其包含:
從定義可以看出,在同一秒內,在不同的機器上相同進程ID條件下,非常有可能生成相同的ObjectId。
同時可以根據定義判斷出,在給定條件下,ObjectId本身即可描述生成的時間順序
ObjectId的存儲使用Byte數組,而其展現需將Byte數組轉換成字符串進行顯示,所以通常我們看到的ObjectId都類似于:
ObjectId("507f191e810c19729de860ea")
C#定義ObjectId類
View CodeC#實現ObjectId的生成器
View Code使用舉例
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 Console.ForegroundColor = ConsoleColor.Red; 6 7 ObjectId emptyOid = ObjectId.Empty; 8 Console.WriteLine(emptyOid); 9 10 Console.WriteLine(); 11 Console.ForegroundColor = ConsoleColor.Green; 12 13 for (int i = 0; i < 10; i++) 14 { 15 ObjectId oid = ObjectId.NewObjectId(); 16 Console.WriteLine(oid); 17 } 18 19 Console.WriteLine(); 20 Console.ForegroundColor = ConsoleColor.Blue; 21 22 ObjectId existingOid; 23 ObjectId.TryParse("507f191e810c19729de860ea", out existingOid); 24 Console.WriteLine(existingOid); 25 26 Console.ReadKey(); 27 } 28 }本文轉自匠心十年博客園博客,原文鏈接:http://www.cnblogs.com/gaochundong/archive/2013/04/24/csharp_generate_mongodb_objectid.html,如需轉載請自行聯系原作者
總結
以上是生活随笔為你收集整理的C# 生成 MongoDB 中的 ObjectId的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 解决 nfs挂载错误wrong fs t
- 下一篇: c# char unsigned_dll