我正在尝试使用以下方法查询 MongoDB -
List<BsonDocument> list = NoSqlBusinessEntityBase.LoadByWhereClause("peoplecounting",
string.Concat("{siteid:\"", siteid, "\", locationid:\"", location._id ,"\",
StartTime: {$gte:ISODate(\"",old.ToString("yyyy-mm-dd hh:mm:ss"),"\")},
EndTime: {$lte:ISODate(\"",current.ToString("yyyy-MM-dd hh:mm:ss"), "\"\")}}"));
LoadByWhereClause()函数如下-
public static List<BsonDocument> LoadDataByWhere(string table, string whereClause)
{
var collection = db.GetCollection(table);
QueryDocument whereDoc = new QueryDocument(BsonDocument.Parse(whereClause));
var resultSet = collection.Find(whereDoc);
List<BsonDocument> docs = resultSet.ToList();
if (resultSet.Count() > 0)
{
foreach (BsonDocument doc in docs)
{
doc.Set("_id", doc.GetElement("_id").ToString().Split('=')[1]);
}
return docs;
}
else
{
return null;
}
}
即使查询在 MongoDB 控制台中运行良好并返回文档
db.peoplecounting.find({siteid:"53f62abf66455068373665ff", locationid:"53f62bb86645506837366603",
StartTime:{$gte:ISODate("2012-12-03 02:40:00")}, EndTime:{$lte:ISODate("2013-12-03 07:40:00")}}
当我尝试使用 LoadByWhereClause 函数在 C# 中加载时出现错误。错误是 String was not recognized as a valid DateTime. while parsing the whereClause. 我怎么可能解决这个问题?我无法确定这里出了什么问题。
请您参考如下方法:
它不是完全清楚的,但我怀疑问题很可能是您如何格式化日期。这:
old.ToString("yyyy-mm-dd hh:mm:ss")
几乎可以肯定是这样的:
old.ToString("yyyy-MM-dd HH:mm:ss")
或者可能
old.ToString("yyyy-MM-dd'T'HH:mm:ss")
因为:
mm表示分钟。您不希望您的年份和月份之间的分钟值;你想要月份 (MM)hh表示“半天的小时数”(即 1-12)。你想要全天的小时,0-23 (HH)- ISO-8601 使用
T文字来分隔日期和时间。
我注意到您的 current.ToString 更好,但不正确 - 它得到正确的月份,但不是小时。这些不一致的事实是一个开始的问题 - 我建议您编写一个单独的方法来适本地转换 DateTime。
