5

I`m trying to query mongodb for documents where "date" is betwen two dates. Sample data is:

{
        "_id" : ObjectId("4fad0af6709fbc1d481c3e05"),
        "ID" : NumberLong("200930746205085696"),
        "text" : "Forgot my charger...:(",
        "date" : ISODate("2012-06-14T10:49:57Z"),
        "sentiment" : "NEG"
}

My Java code is:

DBCursor cursor = null;
DB db = connect();

    Date startDate = new Date(System.currentTimeMillis() - (long)(numOfTimePeriods+1)*time);
    Date endDate = new Date(System.currentTimeMillis() - (long)numOfTimePeriods*time);
    DBObject query = new BasicDBObject();
    query.put("date", new BasicDBObject("$gt", startDate).append("$lte", endDate));

    cursor = db.getCollection("status").find(query);

but the cursor object has no results.

Query object looks like this:

{ "date" : { "$gt" : { "$date" : "2012-05-15T00:16:15.184Z"} , "$lte" : { "$date" : "2012-06-14T10:16:15.184Z"}}}

I suspect the problem is the date representation in DB. Any suggestions on this?

4

2 回答 2

1

$date 表示只是 Java 驱动程序中的 toString 表示,即 Date。它使用严格的 JSON/BSON 表示,而不是扩展的 10gen BSON,其中值可以像在 shell 中一样表示为对象。您不应该尝试使用这样的 toString 输出在 shell 中进行查询,因为它在很多情况下都不起作用。

于 2013-01-03T07:10:15.893 回答
-1

您不应该在查询中使用and 运算符吗?

db.foo.find( { $and: [ { date: { $gt: startDate } }, {date : { $lt: endDate} }  ] } )
于 2012-06-14T09:48:32.417 回答