How to execute MongoDB native query (JSON) using mongo-java-driver only?

Charudatta Joshi picture Charudatta Joshi · Nov 3, 2017 · Viewed 8.5k times · Source

How to fire mongo native queries using java-mongo-driver only.

No Spring-Data or EclipseLink or Hibernate OGM, Only using java-mongo-driver

Sample query :

db.orders.aggregate([
   {
      $unwind: "$specs"
   },
   {
      $lookup:
         {
            from: "inventory",
            localField: "specs",
            foreignField: "size",
            as: "inventory_docs"
        }
   },
   {
      $match: { "inventory_docs": { $ne: [] } }
   }
])

Answer

glytching picture glytching · Nov 3, 2017

If your question is:

Can I pass the above string into the Java driver and have the driver execute it?

Then you could use the db.eval command. For example:

MongoDatabase database = mongoClient.getDatabase("...");

Bson command = new Document("eval", "db.orders.aggregate([\n" +
        "   {\n" +
        "      $unwind: \"$specs\"\n" +
        "   },\n" +
        "   {\n" +
        "      $lookup:\n" +
        "         {\n" +
        "            from: \"inventory\",\n" +
        "            localField: \"specs\",\n" +
        "            foreignField: \"size\",\n" +
        "            as: \"inventory_docs\"\n" +
        "        }\n" +
        "   },\n" +
        "   {\n" +
        "      $match: { \"inventory_docs\": { $ne: [] } }\n" +
        "   }\n" +
        "])");
Document result = database.runCommand(command);

But ... the db.eval command is deprecated and its usage is not advised. The MongoDB Java driver can be used to execute your aggregation but not in its 'string form', instead you would use the Java driver's aggregation helpers to create a Java form of your aggregation command. Plenty of details on this in the docs.

Here's an (untested) example using a 3.x MongoDB Java Driver ...

MongoCollection<Document> collection = mongoClient.getDatabase("...").getCollection("...");

AggregateIterable<Document> documents = collection.aggregate(Arrays.asList(
        // the unwind stage
        new Document("$unwind", "$specs"),

        // the lookup stage
        new Document("$lookup", new Document("from", "inventory")
                .append("localField", "specs")
                .append("foreignField", "size")
                .append("as", "inventory_docs")),

        // the match stage
        new Document("$match", new Document("inventory_docs", new BasicDBObject("$ne", new String[0])))
));

.. this might help you to see the form of translation from shell script to Java.