我需要在Java中进行查询,以便在mongo中搜索日期。要在罗盘上搜索,此查询有效 {“ createdTime”:ISODate('2018-10-10 15:01:40.354')}
有人会知道如何将这个查询放入BasicDBObject查询中,然后我可以这样使用:
mongoCollection.find(查询)
答案 0 :(得分:0)
希望对您有所帮助。
首先我们插入:
public void insertMany(MongoCollection<Document> coll) throws Exception {
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Document newValue0 = new Document("a", "1").append("b", "2").append("c", "3").append("x", new Date());
Document newAlphs1 = new Document("a", "2").append("b", "5").append("c", "55").append("x", sdf.parse("2018-08-10 14:23:35"));
Document newAlphs2 = new Document("a", "3").append("b", "9").append("c", "46").append("x", sdf.parse("2018-07-09 14:23:35"));
Document newAlphs3 = new Document("a", "3").append("b", "9").append("c", "46").append("x", sdf.parse("2018-06-15 14:23:35"));
coll.insertMany(Arrays.asList(newValue0, newAlphs1, newAlphs2, newAlphs3));
}
找到后:
public void findByFilterDates(MongoCollection<Document> coll) throws Exception {
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// for equal
Bson filter = Filters.and(Filters.eq("x",sdf.parse("2018-06-15 14:23:35")));
List<Document> docs = coll.find(filter).into(new ArrayList<Document>());
//for greater than
Bson filter2 = Filters.and(Filters.gt("x",sdf.parse("2018-08-10 14:23:35")));
List<Document> docs2 = coll.find(filter2).into(new ArrayList<Document>());
//for greater than
Bson filter3 = Filters.and(Filters.gt("x",sdf.parse("2018-08-10 14:23:00")), Filters.lt("x",sdf.parse("2018-06-15 14:23:50")));
List<Document> docs3 = coll.find(filter3).into(new ArrayList<Document>());
}