我正在使用 Newtonsoft JsonTextWriter 手动序列化多个 POCO,并将结果保存为 MongoDB BsonDocument。
//
// POCO to store in MongoDB
public class Session
{
public DateTime? StartUTCTimestamp { get; set; }
public DateTime? StartTimestamp { get; set; }
public DateTime? EndTimestamp { get; set; }
public void ToJSON(ref JsonTextWriter writer)
{
Session session = this;
writer.WriteStartObject(); // {
writer.WritePropertyName("StartUTCTimestamp");
writer.WriteValue(session.StartUTCTimestamp);
writer.WritePropertyName("StartTimestamp");
writer.WriteValue(session.StartTimestamp);
writer.WritePropertyName("EndTimestamp");
writer.WriteValue(session.EndTimestamp);
writer.WriteEndObject(); // }
}
}
测试应用程序中用于导入数据的方法,从 SQL Server 数据库(使用 Telerik 的 Open Access ORM)检索所有 Session 对象,将结果存储在列表中。我通过调用在 POCO 上定义的 ToJSON() 方法(见上文)序列化每个 session ,并传入对 JsonTextWriter 的引用。然后使用 C# MongoDB 驱动程序将生成的 JSON 字符串反序列化为 BsonDocument,然后将其保存到 Mongo。 (下面的示例来自 ASP.NET Web 窗体页面,因此是警告框用户控件)。
private void LoadData()
{
DateTime startDate = new DateTime(2015,12,31,23,59,59);
var collection = _database.GetCollection<BsonDocument>("sessions");
using (DbContext ctx = new DbContext())
{
List<Session> sessions = ctx.Sessions.Where().ToList();
foreach (Session item in sessions)
{
JsonTextWriter writer = null;
try
{
StringWriter sw = new StringWriter();
writer = new JsonTextWriter(sw);
writer.CloseOutput = true;
item.ToJSON(ref writer);
String json = sw.ToString();
BsonDocument doc = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(json);
collection.InsertOne(doc);
this.ucAlertMsg.Show("bg-info", "Completed without exception");
}
catch (Exception ex)
{
while (ex.InnerException != null) { ex = ex.InnerException; }
this.ucAlertMsg.Show("bg-danger", ex.Message);
}
finally
{
writer.Close();
}
}
}
}
这可以很好地保存文档,但是,我无法有效地查询文档,在日期范围内进行过滤。我相信,根据我读过的其他几篇文章和文章,这可能是因为该值存储为字符串而不是“ISODate()”。
//
// This is what IS saved
{
"_id" : ObjectId("5729128cd9017a248cbe6284"),
"StartUTCTimestamp" : "2015-12-15T23:24:06",
"StartTimestamp" : "2015-12-15T18:24:06",
"EndTimestamp" : "2015-12-15T18:26:59",
}
//
// Is this what I need?
{
"_id" : ObjectId("5729128cd9017a248cbe6284"),
"StartUTCTimestamp" : ISODate("2015-12-15T23:24:06"),
"StartTimestamp" : ISODate("2015-12-15T18:24:06"),
"EndTimestamp" : ISODate("2015-12-15T18:26:59"),
}
在我的 LoadData() 方法中,我在 TextWriter 上尝试了一些配置,根据我读过的一些文章,这些配置似乎应该有所帮助......
StringWriter sw = new StringWriter();
writer = new JsonTextWriter(sw);
writer.DateFormatHandling = DateFormatHandling.IsoDateFormat;
writer.CloseOutput = true;
将“IsoDateFormat”分配给编写器上的“DateFormatHanding”设置没有产生任何区别。我还尝试了“MicrosoftDateFormat”,数据仍然存储为字符串,但格式不同。
实际问题
这就是所有设置...问题是“我如何根据日期搜索 MongoDB 文档”?
使用 MongoDB 的 C# 驱动程序允许我使用 Linq 进行搜索。这是我正在使用的 linq 查询。
IMongoCollection<Session> collection = database.GetCollection<Session>("sessions");
DateTime startDate = (this.StartDate.HasValue) ? this.StartDate.Value : DateTime.Now.AddDays(-7);
DateTime endDate = (this.EndDate.HasValue) ? this.EndDate.Value : DateTime.Now;
var data = collection.Find<Session>(e => e.StartTimestamp.Value >= startDate && e.StartTimestamp.Value <= endDate).ToList();
由于 JSON 直接映射回 Session POCO,我应该能够使用该类型(?)。我可以成功过滤 Session POCO 中的其他字段。只是约会让我感到不适。
我猜测我的实现中可能存在问题或疏忽,或者由于数据是以字符串形式存储的,因此无法将其与 Date(?) 进行比较。
如有任何见解,我们将不胜感激。
谢谢, -G
请您参考如下方法:
过滤器表达式中的日期必须使用 BsonValue.Create(yourDate) 创建;
示例:
IMongoDatabase db = GetMongoDbConnection();
IMongoCollection<BsonDocument> collection = db.GetCollection<BsonDocument> ("yourCollectionName");
DateTime date = BsonValue.Create(DateTime.Now.Date);
var filter = Builders<BsonDocument>.Filter.Gt("dateFieldToFilterOn", date);
List<BsonDocument> bsonDocuments = await collection.Find(filter).ToListAsync();
