熊咚咚 發表於 2020-8-16 17:24:00

用过 mongodb 吧, 这三个大坑踩过吗?

<h2 id="一背景">一:背景</h2>
<h3 id="1-讲故事">1. 讲故事</h3>
<p>前段时间有位朋友在微信群问,在向 mongodb 中插入的时间为啥取出来的时候少了 8 个小时,8 在时间处理上是一个非常敏感的数字,又吉利又是一个普适的话题,后来我想想初次使用 mongodb 的朋友一定还会遇到各种新坑,比如说: 插入的数据取不出来,看不爽的 ObjectID,时区不对等等,这篇就和大家一起聊一聊。</p>
<h2 id="二-1号坑-插进去的数据取不出来">二: 1号坑 插进去的数据取不出来</h2>
<h3 id="1-案例展示">1. 案例展示</h3>
<p>这个问题是使用强类型操作 mongodb 你一定会遇到的问题,案例代码如下:</p>
<pre><code class="language-C#">
    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&lt;Student&gt;("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; }
    }

</code></pre>
<p><img src="https://img2020.cnblogs.com/other/214741/202008/214741-20200816172412559-841199423.png" alt="" loading="lazy"></p>
<p>我去,这么简单的一个操作还报错,要初学到放弃吗? 挺急的,在线等!</p>
<h3 id="2-堆栈中深挖源码">2. 堆栈中深挖源码</h3>
<p>作为一个码农还得有钻研代码的能力,从错误信息中看说有一个 <code>_id</code> 不匹配 student 中的任何一个字段,然后把全部堆栈找出来。</p>
<pre><code class="language-C#">
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(IEnumerable`1 source)
   at Newtonsoft.Test.Program.Main(String[] args) in E:\crm\JsonNet\Newtonsoft.Test\Program.cs:line 32

</code></pre>
<p>接下来就用 dnspy 去定位一下 <code>MongoQueryProviderImpl.Execute</code> 到底干的啥,截图如下:</p>
<p><img src="https://img2020.cnblogs.com/other/214741/202008/214741-20200816172412736-287265228.png" alt="" loading="lazy"></p>
<p>我去,这代码硬核哈,用了 <code>LambdaExpression</code> 表达式树,我们知道表达式树用于将一个领域的查询结构转换为另一个领域的查询结构,但要寻找如何构建这个方法体就比较耗时间了,接下来还是用 dnspy 去调试看看有没有更深层次的堆栈。</p>
<p><img src="https://img2020.cnblogs.com/other/214741/202008/214741-20200816172412978-1785262618.png" alt="" loading="lazy"></p>
<p>这个堆栈信息就非常清楚了,原来是在 <code> MongoDB.Bson.Serialization.BsonClassMapSerializer.DeserializeClass</code> 方法中出了问题,接下来找到问题代码,简化如下:</p>
<pre><code class="language-C#">
public TClass DeserializeClass(BsonDeserializationContext context)
{
        while (reader.ReadBsonType() != BsonType.EndOfDocument)
        {
                TrieNameDecoder&lt;int&gt; trieNameDecoder = new TrieNameDecoder&lt;int&gt;(elementTrie);
                string text = reader.ReadName(trieNameDecoder);
                if (trieNameDecoder.Found)
                {
                        int value = trieNameDecoder.Value;
                        BsonMemberMap bsonMemberMap = allMemberMaps;
                }
                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();
                }
        }
}

</code></pre>
<p>上面的代码逻辑非常清楚,要么 student 中存在 _id 字段,也就是 <code>trieNameDecoder.Found</code>,要么使用 忽略未知的元素,也就是 <code>this._classMap.IgnoreExtraElements</code>,添加字段容易,接下来看看怎么让 IgnoreExtraElements = true,找了一圈源码,发现这里是关键:</p>
<p><img src="https://img2020.cnblogs.com/other/214741/202008/214741-20200816172413227-93037569.png" alt="" loading="lazy"></p>
<p>也就是: <code>foreach (IBsonClassMapAttribute bsonClassMapAttribute in classMap.ClassType.GetTypeInfo().GetCustomAttributes(false).OfType&lt;IBsonClassMapAttribute&gt;())</code>这句话,这里的 classMap 就是 student,只有让 foreach 得以执行才能有望 classMap.IgnoreExtraElements 赋值为 true ,接下来找找看在类上有没有类似 <code>IgnoreExtraElements</code> 的 Attribute,嘿嘿,还真有一个类似的: <code>BsonIgnoreExtraElements</code> ,如下代码:</p>
<pre><code class="language-C#">
   
    public class Student
    {
      public string StudentName { get; set; }

      public DateTime Created { get; set; }
    }

</code></pre>
<p>接下来执行一下代码,可以看到问题搞定:</p>
<p><img src="https://img2020.cnblogs.com/other/214741/202008/214741-20200816172413421-1558665877.png" alt="" loading="lazy"></p>
<p>如果你想验证的话,可以继续用 dnspy 去验证一下源码哈,如下代码所示:</p>
<p><img src="https://img2020.cnblogs.com/other/214741/202008/214741-20200816172413589-1067003557.png" alt="" loading="lazy"></p>
<p>接下来还有一种办法就是增加 _id 字段,如果你不知道用什么类型接,那就用object就好啦,后续再改成真正的类型。</p>
<p><img src="https://img2020.cnblogs.com/other/214741/202008/214741-20200816172413787-1295606849.png" alt="" loading="lazy"></p>
<h2 id="三-2号坑-datetime-时区不对">三: 2号坑 DateTime 时区不对</h2>
<p>如果你细心的话,你会发现刚才案例中的 Created 时间是 <code>2020/8/16 4:24:57</code>, 大家请放心,我不会傻到凌晨4点还在写代码,好了哈,看看到底问题在哪吧, 可以先看看 mongodb 中的记录数据,如下:</p>
<pre><code class="language-C#">
{
    "_id" : ObjectId("5f38b83e0351908eedac60c9"),
    "StudentName" : "hxc",
    "Created" : ISODate("2020-08-16T04:38:22.587Z")
}

</code></pre>
<p>从 ISODate 可以看出,这是格林威治时间,按照0时区存储,所以这个问题转成了如何在获取数据的时候,自动将 ISO 时间转成 Local 时间就可以了,如果你看过底层源码,你会发现在 mongodb 中每个实体的每个类型都有一个专门的 <code>XXXSerializer</code>,如下图:</p>
<p><img src="https://img2020.cnblogs.com/other/214741/202008/214741-20200816172413981-1566572155.png" alt="" loading="lazy"></p>
<p>接下来就好好研读一下里面的<code>Deserialize</code> 方法即可,代码精简后如下:</p>
<pre><code class="language-C#">
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;
}

</code></pre>
<p>可以看出,如果当前的<code>this._kind= DateTimeKind.Local</code> 的话,就将 UTC 时间转成 Local 时间,如果你有上一个坑的经验,你大概就知道应该也是用特性注入的,</p>
<pre><code class="language-C#">
   
    public DateTime Created { get; set; }

</code></pre>
<p>不信的话,我调试给你看看哈。</p>
<p><img src="https://img2020.cnblogs.com/other/214741/202008/214741-20200816172414166-1989661707.png" alt="" loading="lazy"></p>
<p>接下来再看看 <code>this._kind</code> 是怎么被赋的。</p>
<p><img src="https://img2020.cnblogs.com/other/214741/202008/214741-20200816172414384-1775239777.png" alt="" loading="lazy"></p>
<p><img src="https://img2020.cnblogs.com/other/214741/202008/214741-20200816172414507-800313325.png" alt="" loading="lazy"></p>
<h2 id="四-3号坑-自定义objectid">四: 3号坑 自定义ObjectID</h2>
<p>在第一个坑中,不知道大家看没看到类似这样的语句: <code>ObjectId("5f38b83e0351908eedac60c9")</code> ,乍一看像是一个 GUID,当然肯定不是,这是mongodb自己组建了一个 number 组合的十六进制表示,姑且不说性能如何,反正看着不是很舒服,毕竟大家都习惯使用 int/long 类型展示的主键ID。</p>
<p>那接下来的问题是:如何改成我自定义的 number ID 呢? 当然可以,只要实现<code>IIdGenerator</code> 接口即可,那主键ID的生成,我准备用 <code>雪花算法</code>,完整代码如下:</p>
<pre><code class="language-C#">
    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&lt;Student&gt;("student");

            table.InsertOne(new Student() { Created = DateTime.Now });
            table.InsertOne(new Student() { Created = DateTime.Now });
      }
    }

    class Student
    {
      
      public long ID { get; set; }

      
      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;
      }
    }

</code></pre>
<p>然后去看一下 mongodb 生成的 json:</p>
<p><img src="https://img2020.cnblogs.com/other/214741/202008/214741-20200816172414705-6812459.png" alt="" loading="lazy"></p>
<h2 id="四-总结">四: 总结</h2>
<p>好了,这三个坑,我想很多刚接触 mongodb 的朋友是一定会遇到的困惑,总结一下方便后人乘凉,结果不重要,重要的还是探索问题的思路和不择手段😄😄😄。</p>
<h3 id="如您有更多问题与我互动扫描下方进来吧">如您有更多问题与我互动,扫描下方进来吧~</h3>
<img src="https://img2020.cnblogs.com/blog/214741/202008/214741-20200819234337765-350459746.jpg" width="600" height="200" alt="图片名称" align="center"><br><br>
来源:https://www.cnblogs.com/huangxincheng/p/13513303.html
頁: [1]
查看完整版本: 用过 mongodb 吧, 这三个大坑踩过吗?