How to return raw JSON directly from a mongodb query in Java?

As Oliver points out, you can use Spring Data for that, but an alternative which you may or may not prefer would be to use MongoDB's more low-level Java Driver. Take a look at the MongoDB Java Driver 3.x or MongoDB Java Driver 2.x documentation for instructions on using that driver.

Basically, what you need to do is this:

MongoDB Java Driver 3.x

MongoClient mongoClient = new MongoClient();
MongoDatabase db = mongoClient.getDatabase("test");
MongoCollection coll = db.getCollection("testCollection");    
BasicDBObject query = new BasicDBObject("_id", "51a29f6413dc992c24e0283e");

try (MongoCursor<Document> cursor = collection.find(query).iterator()) {
    while(cursor.hasNext()) {
        System.out.println(cursor.next());
    }
}

MongoDB Java Driver 2.x

MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB("test");
DBCollection coll = db.getCollection("testCollection");    
BasicDBObject query = new BasicDBObject("_id", "51a29f6413dc992c24e0283e");

try (DBCursor cursor = coll.find(query)) {
    while(cursor.hasNext()) {
        System.out.println(cursor.next());
    }
}

That will print out all the documents in the collection that have a field _id with a value 51a29f6413dc992c24e0283e.


There's two way's you can do this right now:

1. Using the CollectionCallback on MongoTemplate

You can use a CollectionCallback to deal with the returned DBObject directly and simply toString() it:

template.execute("jvmInfo", new CollectionCallback<String>() {
  String doInCollection(DBCollection collection) {
    DBCursor cursor = collection.find(query)
    return cursor.next().toString()
  }
}

Yo'll still get the exception translation into Spring's DataAccessExceptions. Note, that this is slightly brittle as we expect only a single result to be returned for the query but that's probably something you have to take care of when trying to produce a String anyway.

2. Register a Converter from DBObject to String

You can implement a Spring Converter to do the toString() for you.

class DBObjectToStringConverter implements Converter<DBObject, String> {
  public String convert(DBObject source) {
    return source == null ? null : source.toString();
  }
}

You can then either use the XML configuration or override customConversions() to return a new CustomConversions(Arrays.asList(new DBObjectToStringConverter())) to get it registered with your MongoConverter. You can then simply do the following:

String result = mongoTemplate.findOne(basicQuery, String.class, "jvmInfo");

I will add the just showed converter to Spring Data MongoDB and register it by default for the upcoming 1.3 GA release and port the fix back to 1.2.x as part of the fix for DATAMONGO-743.