Search code examples
jsonmongodbmongodb-java

How to return mongodb in specific json layout?


I have some test data that i am querying using the Java mongodb client. I am just familiarizing myself with the platform and have been successfully been able to run some basic queries.

public class returnJSON {

    public static void main(String[] args) {

        try {
            MongoClient mongoClient = new MongoClient("localhost", 27017);
            DB db = mongoClient.getDB("test");

            DBCollection table = db.getCollection("zips");

            BasicDBObject searchQuery = new BasicDBObject();
            searchQuery.put("pop", new BasicDBObject("$gt", 25000).append("$lt", 26000));

            DBCursor cursor = table.find(searchQuery);

            while (cursor.hasNext()) {
                System.out.println(cursor.next());
            }
            cursor.close();

        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

However, what I would like to do is turn the standard output the java client gives me..

{
    "city": "HUNTSVILLE",
    "loc": [
        -86.567318,
        34.726866
    ],
    "pop": 25513,
    "state": "AL",
    "_id": "35801"
}
{
    "city": "MONTGOMERY",
    "loc": [
        -86.243394,
        32.383443
    ],
    "pop": 25282,
    "state": "AL",
    "_id": "36109"
}

into just the bits I need, i.e.

{ 
    "city" : "HUNTSVILLE" , 
    "pop" : 25513 
}

{
    "city" : "MONTGOMERY" ,
    "pop" : 25282 
}

I have seen something about BSON and MongoJack, but am not too sure if those are what I need.

The plan is for me to eventually make this information available via REST service, but that will be another question for later on.

Many Thanks.


Solution

  • OK, So after some digging, I found that what I needed was this...

        BasicDBObject searchQuery = new BasicDBObject();
        BasicDBObject fields = new BasicDBObject();
    
        searchQuery.put("pop", new BasicBSONObject("$gt", 25000).append("$lt", 25100));
        fields.put("city", 1);
        fields.put("pop", 1);
        fields.put("_id", 0);
    
        DBCursor cursor = table.find(searchQuery, fields);
    

    This returned...

    { "city" : "FORT ORD" , "pop" : 25009} { "city" : "LAKEWOOD" , "pop" : 25008}

    Which was exactly what I needed.