MongoDB c#驱动程序和DateTime字段

本文关键字:DateTime 字段 驱动程序 MongoDB | 更新日期: 2023-09-27 18:05:30

我正在使用c#驱动程序插入文档到MongoDB集合,其中一个字段类型vs DateTime当我调试应用程序时,我在"FrameTimeStamp"字段中看到服务器时间,我正在传递给MongoDB,这是我的代码:

FrameDocument frameDoc = new FrameDocument();
frameDoc.Frame = imageBA;
frameDoc.EventCodeId = 1;
frameDoc.SesionId = 1;
frameDoc.FrameTimeStamp = DateTime.Now;
frameDoc.ServerUserId = (int)toMongoDt.Rows[0]["ServerUserId"];
frameDoc.TraderId = (int)toMongoDt.Rows[0]["TraderId"];
frameDoc.ActivePick = (int)toMongoDt.Rows[0]["ActivePick"];
frameDoc.TraderName = (string)toMongoDt.Rows[0]["TraderName"];
frameDoc.ServerUserName = (string)toMongoDt.Rows[0]["ServerUserName"];
var mongoCon = "mongodb://127.0.0.1";
MongoClient client = new MongoClient(mongoCon);
var db = client.GetDatabase("Video");
var frameCollection = db.GetCollection<FrameDocument>("Frame");
frameCollection.InsertOne(frameDoc);

在shell中,当我读取数据时,我看到它的格式如下:2016-08-14 t06:10:33 .29 z 和时间不是服务器时间,它的UTC,我怎么能强迫mongo写DateTime当我通过它,?

MongoDB c#驱动程序和DateTime字段

按CSHARP-185

MongoDB将所有DateTimes存储为UTC格式。你提供的任何当地时间都是在数据库中存储时转换为UTC。推荐的方法是总是转换日期时间值到UTC自己之前存储它们在数据库中,这样你就可以完全控制。你也可以告诉c#驱动你想用LocalTime工作,像这样:

[BsonDateTimeOptions(Kind = DateTimeKind.Local)]
public DateTime Date
{ get; set; }