在Mongo DB上搜索ISODate不使用java获取任何记录

时间:2015-06-03 12:05:09

标签: java mongodb date database

我尝试过不同的方法来查找日期范围内的查询数据,但似乎都没有。我已经浏览了StackOverflow上发布的所有问题。

DBCollection findCollection = getMongoUtil().findCollection(collectionName);


// 1st method

BasicDBObject query = new BasicDBObject("createDate", new BasicDBObject("$gt", analyticsSearch.getjStartDate()).append("$lte", analyticsSearch.getjEndDate()));

// 2nd method

query.put("createDate", new BasicDBObject("$gt",new DateTime(analyticsSearch.getjStartDate().getTime())).append("$lte", new DateTime(analyticsSearch.getjEndDate().getTime())));

// 3rd method

query.put("createDate", new BasicDBObject("$gt",analyticsSearch.getjStartDate()).append("$lte", analyticsSearch.getjEndDate()));


// 4th method

QueryBuilder qb = new QueryBuilder();
qb.put("createDate").greaterThan(analyticsSearch.getjStartDate()).lessThan(analyticsSearch.getjEndDate());
BasicDBObject bdo = new BasicDBObject();
bdo.putAll(qb.get());
DBCursor find = findCollection.find(bdo);

构造的查询格式为

query={ "createDate" : { "$gt" : { "$date" : "2014-11-30T18:30:00.000Z"} , "$lte" : { "$date" : "2015-06-03T17:30:00.000Z"}}}

虽然该集合以这种格式保存数据:

{
"_id" : ObjectId("556da50944ae75266d15adb0"),
"createDate" : ISODate("2015-06-02T12:43:53.286Z"),
"name" : "xyz",
"company" : "abc"
}

我猜,查询包含$ date,它正在打破它。请建议如何解决这个问题。

1 个答案:

答案 0 :(得分:0)

只需使用标准的Java日期对象

假设analyticsSearch.getjStartDate()和analyticsSearch.getjEndDate()是java.util.Date对象,请尝试:

query.put("createDate", new BasicDBObject("$gt",analyticsSearch.getjStartDate())).append("$lte", analyticsSearch.getjEndDate())));

对不起,我没有更改你的所有例子: - )

使用以下代码对本地设置进行测试,并按预期工作

    MongoClient mongoClient = new MongoClient("localhost", 27017);
    DB db = mongoClient.getDB("mydb");
    QueryBuilder qb = new QueryBuilder();
    Calendar scal = Calendar.getInstance();
    scal.set(Calendar.YEAR, 2015);
    scal.set(Calendar.MONTH, 0);
    scal.set(Calendar.DAY_OF_MONTH, 20);
    scal.set(Calendar.HOUR_OF_DAY, 11);
    scal.set(Calendar.MINUTE, 15);
    scal.set(Calendar.SECOND, 20);
    scal.set(Calendar.MILLISECOND, 114);
    Calendar ecal = Calendar.getInstance();
    ecal.set(Calendar.YEAR, 2015);
    ecal.set(Calendar.MONTH, 0);
    ecal.set(Calendar.DAY_OF_MONTH, 20);
    ecal.set(Calendar.HOUR_OF_DAY, 13);
    ecal.set(Calendar.MINUTE, 15);
    ecal.set(Calendar.SECOND, 20);
    ecal.set(Calendar.MILLISECOND, 114);

    qb.put("date").greaterThan(scal.getTime()).lessThan(ecal.getTime());

    BasicDBObject bdo = new BasicDBObject();
    bdo.putAll(qb.get());
    DBCollection findCollection = db.getCollection("mycoll");
    DBCursor find = findCollection.find(bdo);

    System.out.println(scal.getTime());
    System.out.println(ecal.getTime());
    System.out.println(find.count());

mycoll中有12329个文档。此查询的计数为65。