Using $filter in MongoDB Java Driver

I have a query that works in MQL. I need to translate it into Java. The query in MQL looks like this

db..aggregate( [
{
$project: {
“MonitoringLocationIdentifier”: 1,
epochTimes: {
$filter: {
input: “$epochTimes”,
as: “epochTime”,
cond: { $and: [ {$gte: [ “$$epochTime”, NumberLong(“0”) ]}, {$lte: ["$$epochTime", NumberLong(“558268020000”)]} ]}
}
},
}
}
] )

The contains documents that look like this
{ “_id” : ObjectId(“633218dfec534a6fe90106b8”), “MonitoringLocationIdentifier”: “Site1”, “epochTimes” : [ NumberLong(“451058760000”), NumberLong(“558189720000”), NumberLong(“516460860000”) ] }

I am trying to get all the documents in the collection but filter the “epochTimes” for every document by a min/max.

Any Java Driver wizards out there?

I would copy your aggregation into Compass and export as Java.

Hi Matt, the Java translation would be:

import static com.mongodb.client.model.Aggregates.project;
import static com.mongodb.client.model.Projections.computed;
import static com.mongodb.client.model.Projections.fields;
...
project(fields(
        computed("MonitoringLocationIdentifier", 1),
        computed("epochTimes", new Document("$filter",
                new Document("input", "$epochTimes")
                .append("as", "epochTime")
                .append("cond", new Document("$and", Arrays.asList(
                        new Document("$gte", Arrays.asList("$$epochTime", 0L)),
                        new Document("$lte", Arrays.asList("$$epochTime", 558268020000L))
                )))
        ))
))

The Java driver offers static builder methods for some but not all parts of your MQL. Where no builder yet exists, I’ve used Document.

1 Like