How to fire mongo native queries using java-mongo-driver only.
No Spring-Data or EclipseLink or Hibernate OGM, Only using
I was running out of time so used following workaround. Will explore Morcos suggestion in detail later. But following code also works.
import com.infrasoft.mongo.MongoClientFactory;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.CommandResult;
import com.mongodb.DB;
import com.mongodb.DBObject;
import com.mongodb.util.JSON;
/**
*
* @author charudatta.joshi
*/
public class TestNaiveQuery1 {
public static void main(String[] args) {
String nativeQuery = "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"
+ "])";
DBObject command = new BasicDBObject();
DB db = MongoClientFactory.getMongoClientFactory().getMongoClient().getDB("frms_data_demo");
nativeQuery = "function() { return (" + nativeQuery + ").toArray(); }";
//command.put("eval", "function() { return db." + collectionName + ".find(); }");
command.put("eval", nativeQuery);
CommandResult result = db.command(command);
BasicDBList dbObjList = (BasicDBList) result.toMap().get("retval");
DBObject dbo0 = (BasicDBObject) dbObjList.get(0);
DBObject dbo1 = (BasicDBObject) dbObjList.get(0);
System.out.println(dbObjList.get(0));
System.out.println(dbObjList.get(1));
// .... just loop on dbObjList
}
}