1

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.

1 Answer 1

2

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} ?

Sign up to request clarification or add additional context in comments.

1 Comment

That did it. I put the detailed explanation in the question. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.