@Path("/getdata/{collectionName}/{count}")
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getData(@PathParam("collectionName") String collectionName, @PathParam("count") int count) throws UnknownHostException{
DB db = (new MongoClient("localhost")).getDB("testdb");
DBCollection dbCollection = db.getCollection(collectionName);
BasicDBObject basicDBObject = new BasicDBObject();
basicDBObject.put("name", "mustafa");
DBCursor dbCursor = dbCollection.find(basicDBObject);
String result = "{\" "+ collectionName +" \": [";
int i = 0;
while(dbCursor.hasNext() && i < count){
result += dbCursor.next() + ", ";
i++;
}
result = result.substring(0,result.length()-2);
result += "]}";
return result;
}
答案 0 :(得分:0)
您可以使用com.mongodb.util.JSON.serialize()
方法将对象序列化为JSON并返回。