前段时间有位朋友在微信群问,在向 mongodb 中插入的时间为啥取出来的时候少了 8 个小时,8 在时间处理上是一个很是敏感的数字,又吉利又是一个普适的话题,后来我想一想初次使用 mongodb 的朋友必定还会遇到各类新坑,好比说: 插入的数据取不出来,看不爽的 ObjectID,时区不对等等,这篇就和你们一块儿聊一聊。算法
这个问题是使用强类型操做 mongodb 你必定会遇到的问题,案例代码以下:mongodb
class Program { static void Main(string[] args) { var client = new MongoClient("mongodb://192.168.1.128:27017"); var database = client.GetDatabase("school"); var table = database.GetCollection<Student>("student"); table.InsertOne(new Student() { StudentName = "hxc", Created = DateTime.Now }); var query = table.AsQueryable().ToList(); } } public class Student { public string StudentName { get; set; } public DateTime Created { get; set; } }
我去,这么简单的一个操做还报错,要初学到放弃吗? 挺急的,在线等!express
做为一个码农还得有钻研代码的能力,从错误信息中看说有一个 _id
不匹配 student 中的任何一个字段,而后把所有堆栈找出来。json
System.FormatException HResult=0x80131537 Message=Element '_id' does not match any field or property of class Newtonsoft.Test.Student. Source=MongoDB.Driver StackTrace: at MongoDB.Driver.Linq.MongoQueryProviderImpl`1.Execute(Expression expression) at MongoDB.Driver.Linq.MongoQueryableImpl`2.GetEnumerator() at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) at Newtonsoft.Test.Program.Main(String[] args) in E:\crm\JsonNet\Newtonsoft.Test\Program.cs:line 32
接下来就用 dnspy 去定位一下 MongoQueryProviderImpl.Execute
到底干的啥,截图以下:微信
我去,这代码硬核哈,用了 LambdaExpression
表达式树,咱们知道表达式树用于将一个领域的查询结构转换为另外一个领域的查询结构,但要寻找如何构建这个方法体就比较耗时间了,接下来仍是用 dnspy 去调试看看有没有更深层次的堆栈。ide
这个堆栈信息就很是清楚了,原来是在 MongoDB.Bson.Serialization.BsonClassMapSerializer.DeserializeClass
方法中出了问题,接下来找到问题代码,简化以下:性能
public TClass DeserializeClass(BsonDeserializationContext context) { while (reader.ReadBsonType() != BsonType.EndOfDocument) { TrieNameDecoder<int> trieNameDecoder = new TrieNameDecoder<int>(elementTrie); string text = reader.ReadName(trieNameDecoder); if (trieNameDecoder.Found) { int value = trieNameDecoder.Value; BsonMemberMap bsonMemberMap = allMemberMaps[value]; } else { if (!this._classMap.IgnoreExtraElements) { throw new FormatException(string.Format("Element '{0}' does not match any field or property of class {1}.", text, this._classMap.ClassType.FullName)); } reader.SkipValue(); } } }
上面的代码逻辑很是清楚,要么 student 中存在 _id 字段,也就是 trieNameDecoder.Found
, 要么使用 忽略未知的元素,也就是 this._classMap.IgnoreExtraElements
,添加字段容易,接下来看看怎么让 IgnoreExtraElements = true,找了一圈源码,发现这里是关键:this
也就是: foreach (IBsonClassMapAttribute bsonClassMapAttribute in classMap.ClassType.GetTypeInfo().GetCustomAttributes(false).OfType<IBsonClassMapAttribute>())
这句话,这里的 classMap 就是 student,只有让 foreach 得以执行才能有望 classMap.IgnoreExtraElements 赋值为 true ,接下来找找看在类上有没有相似 IgnoreExtraElements
的 Attribute,嘿嘿,还真有一个相似的: BsonIgnoreExtraElements
,以下代码:调试
[BsonIgnoreExtraElements] public class Student { public string StudentName { get; set; } public DateTime Created { get; set; } }
接下来执行一下代码,能够看到问题搞定:code
若是你想验证的话,能够继续用 dnspy 去验证一下源码哈,以下代码所示:
接下来还有一种办法就是增长 _id 字段,若是你不知道用什么类型接,那就用object就好啦,后续再改为真正的类型。
若是你细心的话,你会发现刚才案例中的 Created 时间是 2020/8/16 4:24:57
, 你们请放心,我不会傻到凌晨4点还在写代码,好了哈,看看到底问题在哪吧, 能够先看看 mongodb 中的记录数据,以下:
{ "_id" : ObjectId("5f38b83e0351908eedac60c9"), "StudentName" : "hxc", "Created" : ISODate("2020-08-16T04:38:22.587Z") }
从 ISODate 能够看出,这是格林威治时间,按照0时区存储,因此这个问题转成了如何在获取数据的时候,自动将 ISO 时间转成 Local 时间就能够了,若是你看过底层源码,你会发如今 mongodb 中每一个实体的每一个类型都有一个专门的 XXXSerializer
,以下图:
接下来就好好研读一下里面的 Deserialize
方法便可,代码精简后以下:
public override DateTime Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) { IBsonReader bsonReader = context.Reader; BsonType currentBsonType = bsonReader.GetCurrentBsonType(); DateTime value; switch (this._kind) { case DateTimeKind.Unspecified: case DateTimeKind.Local: value = DateTime.SpecifyKind(BsonUtils.ToLocalTime(value), this._kind); break; case DateTimeKind.Utc: value = BsonUtils.ToUniversalTime(value); break; } return value; }
能够看出,若是当前的 this._kind= DateTimeKind.Local
的话,就将 UTC 时间转成 Local 时间,若是你有上一个坑的经验,你大概就知道应该也是用特性注入的,
[BsonDateTimeOptions(Kind = DateTimeKind.Local)] public DateTime Created { get; set; }
不信的话,我调试给你看看哈。
接下来再看看 this._kind
是怎么被赋的。
在第一个坑中,不知道你们看没看到相似这样的语句: ObjectId("5f38b83e0351908eedac60c9")
,乍一看像是一个 GUID,固然确定不是,这是mongodb本身组建了一个 number 组合的十六进制表示,姑且不说性能如何,反正看着不是很舒服,毕竟你们都习惯使用 int/long 类型展现的主键ID。
那接下来的问题是:如何改为我自定义的 number ID 呢? 固然能够,只要实现 IIdGenerator
接口便可,那主键ID的生成,我准备用 雪花算法
,完整代码以下:
class Program { static void Main(string[] args) { var client = new MongoClient("mongodb://192.168.1.128:27017"); var database = client.GetDatabase("school"); var table = database.GetCollection<Student>("student"); table.InsertOne(new Student() { Created = DateTime.Now }); table.InsertOne(new Student() { Created = DateTime.Now }); } } class Student { [BsonId(IdGenerator = typeof(MyGenerator))] public long ID { get; set; } [BsonDateTimeOptions(Kind = DateTimeKind.Local)] public DateTime Created { get; set; } } public class MyGenerator : IIdGenerator { private static readonly IdWorker worker = new IdWorker(1, 1); public object GenerateId(object container, object document) { return worker.NextId(); } public bool IsEmpty(object id) { return id == null || Convert.ToInt64(id) == 0; } }
而后去看一下 mongodb 生成的 json:
好了,这三个坑,我想不少刚接触 mongodb 的朋友是必定会遇到的困惑,总结一下方便后人乘凉,结果不重要,重要的仍是探索问题的思路和不择手段😄😄😄。