Mongodb + Java驱动程序。按日期范围搜索

编程入门 行业动态 更新时间:2024-10-27 20:27:12
本文介绍了Mongodb + Java驱动程序。按日期范围搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是我第一次使用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中操作你可以检查一下。 joda-time.sourceforge/

Datetime object is a library which simplies date manipulation in java. You can check that out. joda-time.sourceforge/

此外,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驱动程序。按日期范围搜索

本文发布于:2023-11-22 12:54:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617490.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:驱动程序   按日   Mongodb   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!