【问题标题】:Date getting compared as string in MongoDB在 MongoDB 中将日期作为字符串进行比较
【发布时间】:2013-05-23 16:05:30
【问题描述】:

我正在尝试比较以下集合中的日期

$db.notifications.find() { "_id" : ObjectId(“51a4467be4b0142fc8b80eda”),“时间”:“5 月 28 日星期二 11:24:03 IST 2013”​​,“KEY”:“VALUE1”} {“_id”: ObjectId(“51a4467be4b0142fc8b80edb”),“时间”:“5 月 28 日星期二 11:24:03 IST 2013", "KEY" : "VALUE2" }

使用

$db.notifications.find({ "time" : { "$gt" : "IST 5 月 31 日星期五 00:00:00 2013"}})

但我观察到的是它正在比较将“时间”视为 字符串不是日期,因此第二个命令同时返回我 条目。

$ db.notifications.find({ "time" : { "$gt" : "IST 5 月 31 日星期五 00:00:00 2013"}}) { "_id" : ObjectId("51a4467be4b0142fc8b80eda"), "time" : "星期二 5 月 28 日 11:24:03 IST 2013”​​,“KEY”:“VALUE1”} {“_id”: ObjectId(“51a4467be4b0142fc8b80edb”),“时间”:“5 月 28 日星期二 11:24:03 IST 2013", "KEY" : "VALUE2" }

能否请您帮助我正确查询并告诉我如何 正确的版本可以用 JAVA 编写。

非常感谢!!

编辑1:

我正在使用以下代码保存日期

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
dateFormat.setLenient(false);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); 
String nowString = dateFormat.format(new Date()); 
Date nowDate = dateFormat.parse(nowString); 
input.put("formattedDate", nowDate);
DBCollection collection = db.getCollection(<collection name>);
DBObject dbObject = (DBObject) JSON.parse(input.toString());
collection.insert(dbObject);"

并使用查询

DBObject query = QueryBuilder.start().put("formattedDate")
                                     .greaterThan(prevDate).get();
DBCursor cursorDocJSON = collection.find(query);

我看到我只将“时间”保存为日期。为什么还是有问题?

【问题讨论】:

  • 这样做是因为您将其存储为字符串!

标签: java mongodb


【解决方案1】:

我认为你的日期应该是一个 ISODate 对象。目前它在您的查询中是一个字符串。试试下面的方法。

db.coll.find({"time" : { $gte : new ISODate("2013-05-28T20:18:00Z") }});

另外,related link

【讨论】:

  • 这是正在执行的查询。 >>> db.notifications.find({ "time" : { "$gt" : { "$date" : "2013-05-24T18:30:00.000Z"}}})
【解决方案2】:

您的日期似乎存储为字符串而不是 ISODate。如果它被存储为真实日期而不是字符串,您会看到如下内容:

> db.MyCollection.find()
{ "_id" : ObjectId("51a4e4aa3004bc68e4f499e5"), "date" : ISODate("2000-09-29T23:00:00Z") }

确保在保存“时间”字段时将其作为日期插入。如果您使用 Java 驱动程序插入值,则需要确保将时间字段添加到 DBObject 时是 java.util.Date(假设您直接使用 Java 驱动程序而不是某些第三方库)。

当您将其作为日期插入后,您应该能够使用 shell 中的 ISODate 值或通过 Java 驱动程序使用 Date 执行所需的查询类型。

【讨论】:

  • 我正在使用以下代码保存日期 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").; dateFormat.setLenient(false); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); String nowString = dateFormat.format(new Date());日期 nowDate = dateFormat.parse(nowString); input.put("时间", nowDate); DBCollection 集合 = db.getCollection(); DBObject dbObject = (DBObject) JSON.parse(input.toString());集合.插入(dbObject);你能帮我理解我的错误吗?
  • 您评论中的代码是创建一个新的Date对象(new Date()),使用SimpleDateFormatter把它变成一个String(dateFormat.format(new Date()),把它变成返回 到一个日期对象 (dateFormat.parse(nowString))。通过执行 input.put("time", new Date()); 可以用更少的代码行得到相同的结果;但是还是会出错。输入的是什么类型,里面还有什么?
猜你喜欢
  • 1970-01-01
  • 2016-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多