我在MongoDB数据库中有一个集合,它有一些数据,并希望根据日期过滤和查找数据(忽略时间)。
示例数据
{
"_id" : ObjectId("563a38173c2ab9248c02d89e"),
"jobId" : "oAEKMcCIJRIAAAFQbrAR6NDd",
"jobName" : "CheckSessions",
"jobDesc" : "Checks and deletes expired session data",
"jobType" : "Job",
"startTime" : "2015-11-04 00:00:01",
"endTime" : "2015-11-04 00:00:01",
"domainName" : "root",
"recurrencePeriod" : "60",
"recurrencePeriodDesc" : "HOURS(1)"
}
{
"_id" : ObjectId("563a38173c2ab9248c02d89f"),
"jobId" : "C6wKMcCIJXoAAAFQm78R6NCm",
"jobName" : "CheckSessions",
"jobDesc" : "Checks and deletes expired session data",
"jobType" : "Job",
"startTime" : "2015-11-03 23:00:00",
"endTime" : "2015-11-03 23:00:01",
"domainName" : "root",
"recurrencePeriod" : "60",
"recurrencePeriodDesc" : "HOURS(1)"
}
我使用以下命令获取大于特定日期的数据,但它没有给我任何结果。 startTime和endTime都是EST格式。不知道我错过了什么。请指导。
db.jobs.find({"startTime" : { $gt : new Date("2015-11-03")}});
答案 0 :(得分:3)
答案:您只需通过字符串比较查询。
首先,确保startTime列的索引
db.test.ensureIndex({startTime:1})
以下命令在_id:ObjectId("563a38173c2ab9248c02d89f")
db.test.find({
startTime: {
$gte: '2015-11-03 00:00:00',
$lt: '2015-11-04 00:00:00'
}
}).pretty()
通过对我们的查询运行explain(),我们可以看到索引实际上在使用中:
db.test.find({startTime:{$gte:'2015-11-03 00:00:00', $lt:'2015-11-04 00:00:00'}}).explain()
{
"cursor" : "BtreeCursor startTime_1",
"isMultiKey" : false,
"n" : 1,
"nscannedObjects" : 1,
"nscanned" : 1,
"nscannedObjectsAllPlans" : 1,
"nscannedAllPlans" : 1,
"scanAndOrder" : false,
"indexOnly" : false,
"nYields" : 0,
"nChunkSkips" : 0,
"millis" : 0,
"indexBounds" : {
"startTime" : [
[
"2015-11-03 00:00:00",
"2015-11-04 00:00:00"
]
]
},
"server" : "Jaans-MBP.home:27017"
}
我的建议仍然是遵循最佳做法并以适当的日期格式存储您的日期字段,例如
"startTime" : ISODate("2016-05-02T00:00:02Z")
在MongoDB shell中你只需传递
> db.test.insert({startTime:new Date()})
> db.test.find()
// results
{ "_id" : ObjectId("563a49d63b1f1b7df0ebc4f5"), "startTime" : ISODate("2015-11-04T18:09:26.613Z") }