I have native query of mongo db and I want execute the same native query in Java. How can I execute that ?
Hello and welcome to MongoDB forum.
You can use the Java Driver’s MongoDatabase#runCommand method. This is equivalent to Database Comand - Query and Write Operation Commands in mongo
shell
Welcome to the community @97vaqasazeem_N_A,
Can you provide an example of the query you are trying to run? By “native query”, are you referring to a JavaScript query in the mongo
shell?
The Java driver provides a full interface for querying MongoDB. To get started, see MongoDB Java Driver Quick Start and the Java Driver Tutorials.
Regards,
Stennie
Thanks for the reply @Stennie_X . Following is the sample query
db.collectionABC.aggregate(
[
{
$match: { "xxx" : "value" }
},
{ $sort : { created_date : 1} },
{
$group:{
_id: {"xyz" : "$xyz"}
_name: {"abc" : "$abc"},
count: { $sum: 1 }
}
},
{$unwind : "$data"}
]
)
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.
This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.