I am using Java's Morphia library.
Via the command line client I was able to successfully execute the following aggregate
db.shows.aggregate([
{$project: {
_id: 1,
title: 1
}},
{$group:
{
_id: {titleLetter: {$substr: ["$title", 0, 1]}},
count: {$sum: 1},
shows: {$push: "$title"}
}
},
{$sort: {_id: 1}}
]);
Which gives me a list of shows group by the first letter of the show's title.
On the official docs for morphia I see they can take in a DBObject
for AdvancedDatastore.createQuery
but I don't see anything similar for aggregates.
Perhaps i would use something like
BasicDBObject parse = (BasicDBObject) JSON.parse("{$group: { _id: {titleLetter: {$substr: [\"$title\", 0, 1]}}, count: {$sum: 1}, shows: {$push: \"$title\"} } }");
Similarly there is the BasicDBObjectBuilder
approach
DBObject group = BasicDBObjectBuilder.start().push("$group")
.add("_id", "{titleLetter: {$substr: [\"$title\", 0, 1]}}")
.get();
So i can convert the CLI query to something Morphia or at least something from import com.mongodb.*;
to something that Java understands.
I have not been able to get this query to run from Java using any method.
My question is what is a clean approach to converting my aggregate query in the cli to a query in Java and which would eventually return a Java object?