2

I am writing a RESTful service using Jersey and the data is stored in a Mongodb database.

I want to get an item from the database and return the JSON format of it to the clients. And here's my code:

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

        // Build search query
        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("entity_name", entityName);

        DBCursor cursor = coll.find(searchQuery);

        try {
            if (cursor.hasNext()) {
                return cursor.next().toString();
            } else {
                return "Not found.";
            }
        } finally {
            cursor.close();
            mongoClient.close();
        }
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    return "System error.";

But the data I get contains a field called id:

"_id":{
"$oid":"525c8a4df33fa1b05dab6e6c"
},

I want to eliminate this field from the result. How to do it?

And the second question is that: Some of the fields in the result are dates. But the result is like:

"publish_date":{
"$date":"1970-01-15T16:48:14.400Z"
},

I want it to be displayed like:

"publish_date":1970-01-15

I was considering using some third-party libraries like Jackson to store all the data and then return a Jackson object to the client (Jersey can transfer a Jackson object to right JSON format data automatically). But in my case, the number of fields are not fixed. I cannot create an entity class to represent the structure of a result.

Do you guys have some good solutions?

Thx!

4

2 回答 2

1

This is what you want, MongoDB: Read Operations; Projections.

Edit: Sorry, just answered your first question, for the second question: Just use the result and place it into a Date using the SimpleDateFormat. Then you can return it how ever you please.

Easier way in the long run might be to get used to Jackson or something similar, though.

于 2013-10-28T03:53:28.970 回答
1

For the first part of your question, you need to use projection in order to hide certain fields in the result.

DBCursor cursor = coll.find(searchQuery, new BasicDBObject("_id", 0));

For the second part of your question, the MongoDB Java Driver can return a Date object using the following:

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

document = cursor.next();
Date date = document.getDate("publish_date");
String dateStr = dateFormat.format(date);

If you want to put this string back into the result document in order to print as JSON it you can probably do something like:

document.put("publish_date", dateStr);

Otherwise you could just build a BasicDBObject with the new value.

于 2013-10-28T04:55:38.517 回答