【问题标题】:Matching mongo query using Java使用 Java 匹配 mongo 查询
【发布时间】:2014-12-16 15:20:37
【问题描述】:

您好,我想使用 java 查询 MONGO。

我有一个如下查询:
db.flights.find({"timestamp" : {"$lte": new Date("2014-09-05T00:00:00.001Z")}}).count()

输出为 68

当我尝试使用下面的 java 代码时:

table = db.getCollection("flights");
DBObject match = new BasicDBObject();
Date endDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").parse("2014-09-05T00:00:00.001Z");     
match.put("timestamp", new BasicDBObject("$lte", endDate));
int count=table.find(match).count();
System.out.println(collections+" "+"COUNT : "+count);  

输出为 48。

谁能告诉我代码中的问题??

【问题讨论】:

  • 您使用的是什么版本的 Java?如果是JDK 1.7 或更高版本,可以尝试使用yyyy-MM-dd'T'HH:mm:ss.SSSX 模式吗?注意末尾的 X
  • 您的 Java 代码可能使用与服务器不同的时区。我相信the MongoDB server is in UTC,但您的 Java 代码可能在您当地的时区。确保您的 Java 日期也在 UTC

标签: mongodb


【解决方案1】:
saving format 

DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
DateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
className classObject=null; 
Date d1=new Date();
classObject.setDateColumn(format.parse(format.format(d1)));

/---------------------------------------------------/

checking format 

Date d1=new Date();
Date startDate=format.parse((formatDate.format(d1)+" 00:00:00"));
Date endDate=format.parse((formatDate.format(d1)+" 23:59:59"));
classObject=classNameService.classObjectCount(startDate,endDate);


/---------------------------------------------------/

service method

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;

@Autowired(required=true)
private MongoTemplate mongoTemplate;

                       className classObject=null;         
                        Query query = new Query();

            query.addCriteria(org.springframework.data.mongodb.core.query.Criteria.where("testId").in(testId));
            query.addCriteria(org.springframework.data.mongodb.core.query.Criteria.where("testDate").gte(startDate).lte(endDate));
            List<className> classNames=mongoTemplate.find(query, className.class);//put your class name..className 
            if(classNames.size()>0)
                classObject=classNames.get(0);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多