代码之家  ›  专栏  ›  技术社区  ›  Node.JS

Mongo Builder对“DateTime”类字段使用“String”

  •  2
  • Node.JS  · 技术社区  · 7 年前

    DateTime :

    class Model {
        public DateTime Date { get; set; }
    }
    

    在mongo数据库中,它存储为:

    "Date" : "2018-02-01T13:22:08Z"

    代码:

    var builder = Builders<Model>.Filter;
    
    var filter = builder.In("Date", new[]
                {
                   "2018-02-01T13:22:08Z"
                });
    
    // Returns zero element list
    _collection.Find(filter).ToList();
    

      var workingFilter = new BsonDocument()
            {
                { "Date", "2018-02-01T13:22:08Z"}
            };
    
    // This one actually works
    _collection.Find(workingFilter).ToList();
    

    我觉得Mongo的有点不对劲 Builder 当我提供 string 日期时间

    2 回复  |  直到 7 年前
        1
  •  2
  •   mickl    7 年前

    首先是你的.NET DateTime 存储为MongoDB string 这不是默认行为。默认情况下,您应该能够在数据库中看到如下内容:

    "Date" : ISODate("2018-02-01T13:22:08Z")
    

    因此,存储在数据库中的类型与模型中的类型不匹配。请记住,MongoDB先检查类型,然后再检查值,没有类似于强制转换的隐式JavaScript。

    在你的工作示例中 BsonDocument 哪一个 handles dynamic documents

    db.yourCollection.find({"Date" : "2018-02-01T13:22:08Z"})
    

    并返回该文档。

    第二个代码段使用泛型 Filter Builder 所以你指定你关心 Model 班级。

    db.setProfilingLevel(2)
    

    db.system.profile.find({ns: "yourdb.yourcollection"}).sort({ts:-1}).limit(1).pretty()
    

    您将看到由驱动程序生成的查询:

    "command" : {
                "find" : "yourcollection",
                "filter" : {
                        "Date" : {
                                "$in" : [
                                        ISODate("2018-02-01T13:22:08Z")
                                ]
                        }
                },
                "$db" : "yourdb"
        }
    

    日期时间 并将字符串转换为 ISODate 这会导致数据库查询级别上的类型不匹配,这就是为什么没有结果。

    解决?要么存储你的.NET 日期时间 作为 等温线 B辅助文件 以生成查询。

        2
  •  -1
  •   Flydog57    7 年前

    BsonDateTime 而不是 DateTime 在你的C#。如果您想将.NET日期时间公开给C#用户,并且仍然将该日期作为日期保留在Mongo中,请创建两个针对同一备份存储的get/set属性,并使用一些Mongo属性来不保留本机日期时间并重命名BsonDateTime。