【问题标题】:Mongodb Java query for date rangeMongodb Java查询日期范围
【发布时间】:2026-02-14 07:10:01
【问题描述】:

我需要使用 Mongo Driver[3.4.0] for Java 在两个日期范围内查找 mongo db 中的所有记录。

示例: 我有书籍收藏。

{
    "_id" : ObjectId("5acb40d27d63b61cb002bafe"),
    "title" : "WingsOfFire",
    "pub-date" : ISODate("2013-10-02T00:00:00.000Z"),
    "rel-date" : ISODate("2013-11-02T00:00:00.000Z")
}

像上面一样,我有 100 多个文档。

我需要找到所有 pub-date > rel-date 的记录。

我使用的是 Mongo DB 3.2.6 版

我尝试使用 $expr 运算符,但它似乎只适用于 Mongo 3.6+

无法为上述要求找到更清洁的解决方案。

请澄清。

【问题讨论】:

    标签: java mongodb mongodb-query mongodb-java


    【解决方案1】:

    您的用例的 MongoDB(v3.4 之前)shell 命令是:

    db.collection.aggregate([
        {
            "$redact": {
                "$cond": [
                    { "$gt": [ "$pub-date", "$rel-date" ] },
                    "$$KEEP",
                    "$$PRUNE"
                ]
            }
        }
    ])
    

    将这个命令翻译成Java你会得到:

    MongoClient mongoClient = ...;
    
    MongoCollection<Document> collection = mongoClient.getDatabase("...").getCollection("...");
    
    List<Document> documents = collection.aggregate(Arrays.asList(
            new Document("$redact", new Document("$cond",
                    Arrays.asList(new Document("$gt", Arrays.asList("$pub-date", "$rel-date")), "$$KEEP", "$$PRUNE"))
            ))).into(new ArrayList<>());
    
    for (Document document : documents) {
        System.out.println(document.toJson());
    }
    

    给定一个包含这些文档的集合...

    {
        "_id" : ObjectId("5acb40d27d63b61cb002bafe"),
        "title" : "WingsOfFire",
        "pub-date" : ISODate("2013-10-02T00:00:00.000Z"),
        "rel-date" : ISODate("2013-11-02T00:00:00.000Z")
    }
    
    {
        "_id" : ObjectId("5acb662756539a6734e64e4a"),
        "title" : "WingsOfSmoke",
        "pub-date" : ISODate("2013-11-02T00:00:00.000Z"),
        "rel-date" : ISODate("2013-10-02T00:00:00.000Z")
    }
    

    .. 上面的 Java 代码将打印 ...

    { "_id" : { "$oid" : "5acb662756539a6734e64e4a" }, "title" : "WingsOfSmoke", "pub-date" : { "$date" : 1383350400000 }, "rel-date" : { "$date" : 1380672000000 } }
    

    ...因为此文档的 pub-date (2013-11-02T00:00:00.000Z) 在其 rel-date (2013-10-02T00:00:00.000Z) 之后。

    注意:$where 运算符在功能上是等效的,但使用该运算符时会附带一些 limitations

    $where 评估 JavaScript 并且不能利用索引。因此,当您使用标准 MongoDB 运算符(例如,$gt$in)表达查询时,查询性能会提高。

    一般来说,只有当您无法使用其他运算符表达您的查询时,您才应该使用$where。如果您必须使用$where,请尝试至少包含一个其他标准查询运算符来过滤结果集。单独使用 $where 需要进行集合扫描。

    【讨论】:

    • 感谢您的详细解答。
    【解决方案2】:

    你可能想试试$where-Operator:

    db.books.find({ "$where": "this.pub-date > this.rel-date"});
    

    【讨论】: