MongoMapper:查找在指定日期创建的所有文档
我需要编写一个查询来查找在指定日期创建的所有文档。
假设日期是今天。
我尝试过这个:
Document.all(:created_at => Date.parse(Time.now.strftime('%Y/%m/%d')))
但我得到:
无法将 Date 类的对象序列化为 BSON。
感谢您的帮助。
更新 此链接解释了如何执行此操作 日期使用 MongoMapper 进行范围查询。
Document.count( :created_at => { '$gt' => 2.days.ago.midnight, '$lt' => 1.day.ago.midnight } )
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
更新:此链接解释了如何执行此操作使用 MongoMapper 进行日期范围查询。
UPDATE: This link explains how to do so Date Range Queries With MongoMapper.
您的
:created_at
是一个日期(如“具有日期和时间组件的 JavaScript 样式日期”),对吗?您需要找出 UTC 中相关日期的边界,为这些边界构建Time
实例,然后搜索这些时间之间的所有内容。假设您的本地时区已正确配置,并且您想要 2011 年 11 月 21 日创建的所有内容,那么类似这样的内容应该可以帮助您实现:
您还可以使用 Time.new(2011, 11, 21)。 utc 和
Time.new(2011, 11, 22).utc
但我喜欢额外的零来提醒我,我并不是真的只使用一个 日期。Your
:created_at
is a Date (as in "JavaScript-style Date with both date and time-of-day components"), right? You'll need to figure out the boundaries of the date in question in UTC, buildTime
instances for those boundaries, and then search for everything between those times.Assuming that your local time zone is correctly configured and you want everything that was created on 2011-11-21, then something like this should get you there:
You could also use
Time.new(2011, 11, 21).utc
andTime.new(2011, 11, 22).utc
but I like the extra zeros as a reminder that I'm not really working with just a date.只需使用
Time.now
即可。 ruby 驱动程序知道如何处理 Time 对象。或者
然后,您可以测试文档是否会序列化而不在 irb 中抛出错误,如下所示:
如果出现错误,请重试。如果它输出一个序列化的 bson 对象,那么你就可以开始了!
如果您好奇,请查看 mongomapper 驱动程序中
to_mongo
方法的源代码 此处Just use
Time.now
instead. The ruby driver knows how to deal with Time objects.or
Then, you can test if the document will serialize without throwing an error in irb like this:
If you get an error, try again. If it spits out a serialized bson object, you are good to go!
If you are curious, check out the source of the
to_mongo
method in the mongomapper driver here使用@mu-is-to-short 指出的技术来创建日期。
但where语句的格式可以更简单:
Use the technique @mu-is-to-short pointed out to create the date.
But the format of the where statement can be simpler: