简体   繁体   中英

In MongoDB Java Driver how do you use $filter

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

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

The collection 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 searched for mongodb java aggregation and Google yielded this "Java - Aggregation Pipeline" article from them. It walks through some examples, but also mentions that the Compass tool has an Export Pipeline to Specific Language functionality.

So after opening Compass I used CREATE NEW -> Pipeline from text and pasted in your MQL from above. After it was loaded I clicked EXPORT TO LANGUAGE , chose JAVA in the drop down, added Include Import Statements and it produced the following:

import java.util.Arrays;
import org.bson.Document;

Arrays.asList(new Document("$project", 
    new Document("MonitoringLocationIdentifier", 1L)
            .append("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)))))))))

(There is also a Include Driver Syntax button that seems to be even more verbose if needed).

So I'm no Java Driver wizard, but hope this helps anyway!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM