Mongodb:从mongo shell中的ObjectId执行日期范围查询 [英] Mongodb: Perform a Date range query from the ObjectId in the mongo shell
问题描述
我有一个看起来像这样的收藏集:
I have a collection that looks like this:
{
_id: ObjectId("50a68673476427844b000001"),
other fields
}
我想进行范围查询以查找两个日期之间的记录.我知道我可以从mongo shell var中的ObjectId获取日期:
I want to do a range query to find records between two dates. I know that I can get the date from the ObjectId in the mongo shell var doing this:
var aDate = ObjectId().getTimestamp()
但是(目前为止我无法确定)没有办法创建仅包含时间戳部分的ObjectId-我认为我的理想解决方案是使Mongo Shell代码不起作用:>
but there isn't a way (as far as I can figure out at the moment) to create an ObjectId consisting of just the timestamp portion - I think my ideal solution is non-functioning mongo shell code would be:
var minDate = ObjectId(new Date("2012-11-10"));
var maxDate = ObjectId(new Date("2012-11-17"));
将查找结果与minDate和MaxDate用作范围值.
Use the find with the minDate and MaxDate as the range values.
SHELL中有没有办法做到这一点-我对某些驱动程序产品不感兴趣.
Is there a way to do this in the SHELL - I'm not interested in some of the driver products.
推荐答案
您可以通过2个步骤进行操作:
You can do that in 2 steps:
var objIdMin = ObjectId(Math.floor((new Date('1990/10/10'))/1000).toString(16) + "000
0000000000000")
var objIdMax = ObjectId(Math.floor((new Date('2011/10/22'))/1000).toString(16) + "000
0000000000000")
db.myCollection.find({_id:{$gt: objIdMin, $lt: objIdMax}})
或一步(不太容易理解):
or in one step (what is less readable):
db.myCollection.find({_id:{$gt: ObjectId(Math.floor((new Date('1990/10/10'))/1000).toString(16) + "000
0000000000000"), $lt: ObjectId(Math.floor((new Date('2011/10/10'))/1000).toString(16) + "000
0000000000000")}})
这篇关于Mongodb:从mongo shell中的ObjectId执行日期范围查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!