Question

My question is about configuring the returned type from a MongoDB Java driver query.

I am executing a query which will return multiple objects from MongoDB. I am using the MongoDB Java driver as follows:

DBCollection collection = ...;
DBObject query = new DBObject("someField", "someValue");

collection.find(query);

This returns a DBCursor, which can iterate through a set of DBObjects. Since I want to return raw JSON, I go through each object and use a StringBuilder to aggregate the results into a single String (using DBObject.toString()). This has cased other problems though, because escape characters are included in the final result.

As an example, say I have the two records in the DB:

{
    someField : "someValue"
},
{    
    someField : "someOtherValue"
}

After getting a DBCursor, and building a String with a StringBuilder, the final result is:

String s = "{ someField : \"someValue\" }, { someField : \"someOtherValue\" }";

My ideal solution is to return a single DBObject and call its .toString() method, or (even more ideal) just get that raw straing from Mongo.

As always, any thoughts or suggestions would be greatly appreciated.

Thanks.

EDIT - ANSWERED, THANKS Mzzl

private class SingleStringCollectionCallback implements CollectionCallback {

    private final DBObject dbo = new BasicDBObject("someField", "someValue");
    private final DBObject match = new BasicDBObject("$match", dbo);

    public Object doInCollection(DBCollection collection) throws MongoException, DataAccessException {

        AggregationOutput  ao = collection.aggregate(match);

        /** CommandResult contains the results list (as a BasicDBList) in its "result" field. */
        return ao.getCommandResult().get("result");

    }
}

mongoTemplate.execute(COLLECTION_NAME, new SingleStringCollectionCallback());

The BasicDBList.toString() method serializes the list into a single JSON string. Note that you should let your chosen JSON serializer handle the toString() call, and just pass it the BasicDBList. Otherwise you may find escape characters ("{ someField : \"someValue\" }") in your final result.

Was it helpful?

Solution

Query results from the aggregation framework are a single document. Perhaps you could rewrite your query to use aggregate? Maybe a $group by '_id' following a $match by {someField : someValue} ?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top