sql >> Base de Datos >  >> NoSQL >> MongoDB

Consulta Mongodb Java para el rango de fechas

El comando de shell MongoDB (anterior a v3.4) para su caso de uso es:

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

Traduciendo este comando a Java obtendrás:

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());
}

Dada una colección con estos documentos...

{
    "_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")
}

.. el código Java anterior imprimirá ...

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

... porque la pub-date de este documento (2013-11-02T00:00:00.000Z) es posterior a su rel-date (2013-10-02T00:00:00.000Z).

Nota:el $where El operador es funcionalmente equivalente, pero el uso de ese operador viene con algunas limitaciones :