Native query execution in Java

Here is an example with “native” query usage.

Sample input documents from a books collection:

{ "title" : "Ulysses", "author" : "James Joyce" }
{ "title" : "War and Peace", "author" : "Leo Tolstoy" }
{ "title" : "Anna Karenina", "author" : "Leo Tolstoy" }

// Aggregation pipeline stages
String match = "{ '$match':{ 'author': 'Leo Tolstoy' } }";
String sort = "{ '$sort':{ 'title': 1} }";

// Build pipeline as a Bson
String pipe = match + ", " + sort;
String strcCmd = "{ 'aggregate': 'books', 'pipeline': [" + pipe + "], 'cursor': { } }";
Document bsonCmd = Document.parse(strCmd);

// Execute the native query
Document result = db.runCommand​(bsonCmd);

// Get the output
Document cursor = (Document) result.get("cursor");
List<Document> docs = (List<Document>) cursor.get("firstBatch");
docs.forEach(System.out::println);

Note the way you have to extract the result documents - not very covenient. As @Stennie_X has suggested try using the Java Driver provided API.

As such you can create the “native” Aggregation pipeline in the MongoDB Compass GUI tool using the Aggregation Pipeline Builder and use the option Export to Specific Language (Java). This generates the Java code, which you can copy and use it in your application - pretty simple.

2 Likes