You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Java通过ISODate查询MongoDB中两个日期区间的对象

Java实现MongoDB日期范围查询(对应指定MongoShell命令)

刚好我之前做过类似的转换,直接给你两种可行的Java实现方案,还有关键细节要注意,避免踩坑:

先回顾下你提供的原Mongo Shell查询语句:

db.getCollection('collection').find({"cobDate" : { "$gt" : ISODate("2018-04-04T00:00:00.000Z"), "$lte" : ISODate("2018-04-06T00:00:00.000Z")}})

方式1:使用MongoDB官方驱动的Filters工具类(推荐)

这种写法是官方推荐的,代码简洁易读,减少手动拼接的错误:

import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import org.bson.Document;
import static com.mongodb.client.model.Filters.*;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;

public class MongoDateRangeQuery {
    public static void main(String[] args) {
        // 连接MongoDB,替换成你的实际连接字符串
        try (MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017")) {
            // 获取目标集合:替换"your_database_name"为你的数据库名
            MongoCollection<Document> collection = mongoClient.getDatabase("your_database_name").getCollection("collection");
            
            // 构造UTC时区的日期范围,和MongoDB存储的ISODate时区保持一致
            Date startDate = Date.from(LocalDate.of(2018, 4, 4).atStartOfDay(ZoneId.of("UTC")).toInstant());
            Date endDate = Date.from(LocalDate.of(2018, 4, 6).atStartOfDay(ZoneId.of("UTC")).toInstant());
            
            // 构造查询条件:完全对应MongoShell的$gt和$lte
            Document query = new Document("cobDate", and(gt(startDate), lte(endDate)));
            
            // 执行查询并遍历结果
            try (MongoCursor<Document> cursor = collection.find(query).iterator()) {
                while (cursor.hasNext()) {
                    Document doc = cursor.next();
                    // 这里可以根据业务需求处理文档,比如打印或转成实体类
                    System.out.println(doc.toJson());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

方式2:手动构造查询Document

如果你想更直观地对应MongoShell的结构,也可以手动拼接查询条件:

// 省略重复的导入、连接和日期构造代码,只展示查询核心部分
Date startDate = Date.from(LocalDate.of(2018, 4, 4).atStartOfDay(ZoneId.of("UTC")).toInstant());
Date endDate = Date.from(LocalDate.of(2018, 4, 6).atStartOfDay(ZoneId.of("UTC")).toInstant());

// 手动构造$gt和$lte条件,和MongoShell的JSON结构完全一致
Document dateCriteria = new Document("$gt", startDate)
                          .append("$lte", endDate);
Document query = new Document("cobDate", dateCriteria);

// 执行查询和遍历逻辑和方式1完全相同

关键注意事项

  • 时区问题:一定要用UTC时区构造日期,因为MongoDB存储的ISODate是UTC时区的,如果用本地时区转换,会导致查询结果偏差。
  • 驱动版本:上面的代码基于MongoDB Java Driver 4.x+,如果是3.x版本,MongoClients.create()需要换成new MongoClient(),其他逻辑基本一致。
  • 资源管理:用try-with-resources语法自动关闭MongoClient和Cursor,避免资源泄漏。
  • 日期API:推荐使用Java 8+的java.time包处理日期,比旧的java.util.Date更安全、易用。

内容的提问来源于stack exchange,提问作者Amit Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:09:48