【问题标题】:Query from Vava to MongoDB: find event in a specific date range从 Vava 到 MongoDB 查询:查找特定日期范围内的事件
【发布时间】:2015-04-09 04:04:06
【问题描述】:

我在 MongoDB 中有以下文档:

{
"_id" : NumberLong(44),
"_class" : "la.test.app.server.model.Event",
"orgId" : NumberLong(2),
"typeCode" : 1,
"title" : "Test for notification",
"shortDescription" : "Test for notification",
"description" : "Test for notification",
"price" : "100",
"startDate" : ISODate("2015-02-08T16:30:07.000Z"),
"endDate" : ISODate("2015-02-09T16:00:07.000Z"),
"deleted" : false
}

我需要在所有其他事件中找到这个事件。

我正在尝试用方法做这么简单的事情:

public List<Event> getPendingEvents(Date start, Date end) {
   return mongoOperations.find(
        Query.query(Criteria
         .where("startDate").gte(start).lte(end)
         .and("typeCode").is("1")),

Event.class
);

组装并返回我的查询:

 {
"startDate" : { "$gte" : { "$date" : "2015-02-08T05:29:00.000Z"} ,
                "$lte" : { "$date" : "2015-02-08T05:31:00.000Z"}} ,
"typeCode":"1"
}

这个查询只找到“字段:空,排序:空”:

但是直接查询MongoDB:

db.events.find({
"startDate" : {"$gte" : ISODate("2015-02-08 16:30:07.000Z"),
               "$lt" : ISODate("2015-02-08 16:31:07.000Z")},
"typeCode" : 1})

找到所需的事件。

【问题讨论】:

    标签: java mongodb datetime mongodb-query


    【解决方案1】:

    您是否尝试过使用 SimpleDateFormat... 格式化日期?

    我早就试过了……

    //   Find documents by date of birth
      Date gtDate = null;
      try {
       gtDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").parse("1984-05-010T8:30:00.000Z");
      } catch (ParseException e) {
       e.printStackTrace();
      }
      BasicDBObject dateQueryObj = new BasicDBObject("DateOfBirth",  new BasicDBObject("$lt", gtDate));
      cursor = documents.find(dateQueryObj);
      while(cursor.hasNext()) {
       System.out.println("\n Find documents by date of birth. \n");
          System.out.println(cursor.next());
      }
    

    【讨论】:

      【解决方案2】:

      使用 BasicDBObject 而不是 mongoOperations 接口解决了同样的问题。

      类似的东西:

      BasicDBObject query = new BasicDBObject();
          query = new BasicDBObject("endDate", new BasicDBObject("$gte", start).append("$lte", end)).append("typeCode", 1);
      
      
          List<DBObject> result = collection.find(query).toArray();
      

      【讨论】:

        猜你喜欢
        • 2021-01-03
        • 1970-01-01
        • 1970-01-01
        • 2021-07-13
        • 2013-03-06
        • 1970-01-01
        • 1970-01-01
        • 2023-03-20
        • 2022-07-04
        相关资源
        最近更新 更多