日期范围内的C#MongoDB查询

时间:2018-01-30 10:37:23

标签: c# mongodb datetime

我是C#MongoDB驱动程序的新手,并且有一个关于查询具有日期范围的对象的问题。 这是我的收藏

[
{"ssimTmi":"L","ssimCcd":"AA","ssimSp1":" ","ssimFlt":" 000","ssimIvn":"8 ","ssimLsn":"  ","ssimStc":" ","ssimPop":"05JAN1800XXX00","ssimBeg":"05JAN18","ssimDay":"05","ssimMon":"JAN","ssimYyr":"18","ssimEnd":"00XXX00","ssimDop":"05JAN18","ssimFri":"O","ssimLdd":"AG SSIM PRODUCT   ","ssimDsc":"AG "},

{"ssimTmi":" ","ssimCcd":"AA","ssimSp1":" ","ssimFlt":" 001","ssimIvn":"01","ssimLsn":"01","ssimStc":"J","ssimPop":"07JUN1807JUN18","ssimBeg":"07JUN18","ssimDay":"07","ssimMon":"JUN","ssimYyr":"18","ssimEnd":"07JUN18","ssimDop":"123456 ","ssimFri":" ","ssimLdd":"JFK08000800-05008 ","ssimDsc":"JFK"},

{"ssimTmi":" ","ssimCcd":"CO","ssimSp1":" ","ssimFlt":" 001","ssimIvn":"01","ssimLsn":"01","ssimStc":"J","ssimPop":"09NOV1809NOV18","ssimBeg":"09NOV18","ssimDay":"09","ssimMon":"NOV","ssimYyr":"18","ssimEnd":"09NOV18","ssimDop":"123456 ","ssimFri":" ","ssimLdd":"JFK08000800-05008 ","ssimDsc":"JFK"}
]

当我们将Date作为输入时,我想写一个查询来获取“ssimDsc”。如果我给出日期为03MAR18 ......它应该返回“ssimBeg”落在03MAR18和03MAR18之后的所有条目的集合......它不应该显示JAN和FEB数据..

你可以帮忙实现这个目标。

1 个答案:

答案 0 :(得分:0)

我不认为这是推荐的方式,但如果您可以在服务器端运行javascript,则可以构建包含javascript查询的BsonDocument

例如,以下代码假定在名为“ssi”的集合上提供了System.DateTime targetDate

IMongoCollection<BsonDocument> collection = _database.GetCollection<BsonDocument>("ssi");
string javaScript = "function(){ ";
javaScript += "mlist = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']; ";
javaScript += "month = mlist.indexOf(this.ssimMon); day = parseInt(this.ssimDay); year = parseInt(this.ssimYyr) + 2000; ";
javaScript += "dateItem = new Date(Date.UTC(year, month, day)); ";
javaScript += $"targetDate = new Date(Date.UTC({targetDate.Year}, {targetDate.Month}, {targetDate.Day})); ";
javaScript += "return dateItem > targetDate; }";
BsonJavaScript bScript = new BsonJavaScript(javaScript);
BsonDocument query = new BsonDocument("$where", bScript);

var result = collection.Find(query).ToList();

如果服务器端不接受java脚本,你可以通过遍历完整的结果集来处理它,但这是不可取的。

我希望这会有所帮助。