Mongodb + Java驱动程序。按日期范围搜索 [英] Mongodb + Java Drivers. Search by date range
问题描述
这是我第一次使用Mongodb和java驱动程序。我可以通过命令行使用javascript和Date()对象来查询数据库,但是我在使用驱动程序时遇到问题。根据我的查询,任何人都可以看到问题是什么?感谢
This is my first shot at using Mongodb with the java drivers. I can query the database via command line using javascript and the Date() object, however, I am having trouble using the driver. Based on my query, can anybody see what the problem is? Thanks
Date current = new Date();
DBCollection coll = db.getCollection("messages");
BasicDBObject query = new BasicDBObject("created_on", new BasicDBObject("$gte", new Date(current.getYear(), current.getMonth(), current.getDate())).
append("created_on", new BasicDBObject("$lt", new Date(current.getYear(), current.getMonth() - 1, current.getDate()))));
System.out.println("Query: " + query);
DBCursor cursor = coll.find(query);
查询:{created_on:{$ gte $ date:
2012-12-06T05:00:00.000Z},created_on:{$ lt:{$ date:
2012-11-06T05: 00:00.000Z}}}}
Query: { "created_on" : { "$gte" : { "$date" : "2012-12-06T05:00:00.000Z"} , "created_on" : { "$lt" : { "$date" : "2012-11-06T05:00:00.000Z"}}}}
PS如果不明显,我想在上个月找到所有的记录。
P.S. In case it is not obvious, I'm trying to find all of the records within the last month.
推荐答案
似乎像正在构造查询错误。请尝试以下一个:
Seems like you are constructing the query wrong. Please try the below one:
BasicDBObject query = new BasicDBObject("created_on", //
new BasicDBObject("$gte", new DateTime().toDate()).append("$lt", new DateTime().toDate()));
日期时间
对象是一个简化日期的库在java中操作你可以检查一下。
http://joda-time.sourceforge.net/
Datetime
object is a library which simplies date manipulation in java. You can check that out.
http://joda-time.sourceforge.net/
此外,morphia是通过java驱动程序与mongodb一起工作的一个不错的java对象文档映射(ODM)框架。它可以通过java简化查询。
Also morphia is a nice java object-document-mapper (ODM) framework for working with mongodb through java driver. It simplifies querying through java.
https:// github。 com / jmkgreen / morphia
这篇关于Mongodb + Java驱动程序。按日期范围搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!