1

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.

4

1 回答 1

1

好的,所以经过一番挖掘,我发现我需要的是这个......

    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);

这回...

{“城市”:“奥德堡”,“流行”:25009} {“城市”:“莱克伍德”,“流行”:25008}

这正是我所需要的。

于 2013-07-20T10:05:57.220 回答