问题
I'm trying to convert MongoDb query using aggregation framework using Java driver. I have been helped to create query here How to apply filter for output of aggregation framework of Mongo Db?.
Here is the sample aggregate query:
db.movies.aggregate(
[{
$redact: {
$cond: {
if: {$gt: [{ $avg: "$customerReviews"}, 7 ] },
then: "$$KEEP",
else: "$$PRUNE"
}
}
},
{$skip:1},
{$limit:2}
]
);
I started with:
BasicDBObject avgQuery = new BasicDBObject("$avg", "$customerReviews");
But cannot figure out how to perform {$gt: [{ $avg: "$customerReviews"}, 7 ] }. I think it should be something like gtQuery.put(avgQuery, new BasicDbObject("$gt",7)) but obviously cannot put something other than String in put() function.
Btw, I'm not sure if $redact can be done only using BasicDbObject or I need something like Mongo spring query where two fields are equal which uses Spring Mongo. Hope someone can help me get through the whole query.
回答1:
BasicDBObject
is old 2.x mongo version classes. Use the newer 3.x api classes.
I don't see any helper class to create redact
pipeline in the java driver.
MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("dbname");
MongoCollection<Document> collection = database.getCollection("dbcollection");
List<Document> results = collection.aggregate(Arrays.asList(
new Document("$redact", new Document("$cond",
Arrays.asList(new Document("$gt",
Arrays.asList(new Document("$avg", "$customerReviews"), 7)),
"$$KEEP", "$$PRUNE"))),
Aggregates.skip(1),
Aggregates.limit(2)
)).into(new ArrayList<>());
Alternatively you can use
String redact = "{\n" +
" $redact: {\n" +
" $cond: {\n" +
" if: {$gt: [{ $avg: \"$customerReviews\"}, 7 ] },\n" +
" then: \"$$KEEP\",\n" +
" else: \"$$PRUNE\"\n" +
" }\n" +
" }\n" +
"}";
List<Document> results = collection.aggregate(Arrays.asList(
Document.parse(redact),
Aggregates.skip(1),
Aggregates.limit(2)
)).into(new ArrayList<>());
来源:https://stackoverflow.com/questions/42357768/how-to-write-redact-aggregation-in-java