C# 生成 MongoDB 中的 ObjectId

ObjectId介绍

在MongoDB中,文档(document)在集合(collection)中的存储需要一个唯一的_id字段作为主键。这个_id默认使用ObjectId来定义,因为ObjectId定义的足够短小,并尽最大可能的保持唯一性,同时能被快速的生成。

ObjectId 是一个 12 Bytes 的 BSON 类型,其包含:

  1. 4 Bytes 自纪元时间开始的秒数
  2. 3 Bytes 机器描述符
  3. 2 Bytes 进程ID
  4. 3 Bytes 随机数

从定义可以看出,在同一秒内,在不同的机器上相同进程ID条件下,非常有可能生成相同的ObjectId。
同时可以根据定义判断出,在给定条件下,ObjectId本身即可描述生成的时间顺序

ObjectId的存储使用Byte数组,而其展现需将Byte数组转换成字符串进行显示,所以通常我们看到的ObjectId都类似于:

ObjectId("507f191e810c19729de860ea")

C#定义ObjectId类

C# 生成 MongoDB 中的 ObjectIdView Code

C#实现ObjectId的生成器

C# 生成 MongoDB 中的 ObjectIdView Code

使用举例

C# 生成 MongoDB 中的 ObjectId
 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   }
C# 生成 MongoDB 中的 ObjectId

C# 生成 MongoDB 中的 ObjectId







本文转自匠心十年博客园博客,原文链接:http://www.cnblogs.com/gaochundong/archive/2013/04/24/csharp_generate_mongodb_objectid.html,如需转载请自行联系原作者