Mongodb Java 查询日期范围

Mongodb Java query for date range

我需要使用 Mongo Driver[3.4.0] for Java.

在两个日期范围内找到 mongo 数据库中的所有记录

示例: 我有 本书 Collection.

{
    "_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 数据库版本 3.2.6

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

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

请说明。

您可能想试试 $where-Operator:

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

您的用例的 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 evaluates JavaScript and cannot take advantage of indexes. Therefore, query performance improves when you express your query using the standard MongoDB operators (e.g., $gt, $in).

In general, you should use $where only when you can’t express your query using another operator. If you must use $where, try to include at least one other standard query operator to filter the result set. Using $where alone requires a collection scan.