Skip to content

JAX RS support for MongoDB

Angelo edited this page May 15, 2013 · 7 revisions

Mongo JEE provides [several JAX-RS Provider] (https://github.com/angelozerr/mongo-jee/tree/master/mongo-jee/src/main/java/com/mongodb/jee/jaxrs/providers) which serialize/deserialize DBObject, DBCursor, etc to JSON stream.

Once you have registered those JAX-RS Provider in your Web Application, you can use DBObject, DBCursor and PageResult in your service.

Use DBObject

@GET
@Path("/findOne")
@Produces(MediaType.APPLICATION_JSON)
public DBObject findOne() {
	DB db = mongo.getDB("ecommerce");
	DBCollection col = db.getCollection("products");
	return col.findOne();
}

Use DBCursor

@GET
@Path("/find")
@Produces(MediaType.APPLICATION_JSON)
public DBCursor find() {
	DB db = mongo.getDB("ecommerce");
	DBCollection col = db.getCollection("products");
	return col.find();
}

Use PageResult

@GET
@Path("/findPage")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public PageResult findPage(int fromItemIndex, int toItemIndex) {
	DB db = mongo.getDB("ecommerce");
	DBCollection col = db.getCollection("products");
	return new PageResult(col.find(), fromItemIndex, toItemIndex);
}

Use PageResult and PageRangeRequest

@GET
@Path("/findPageRange")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public PageResult findPage(@HeaderParam("Range") PageRangeRequest range) {
	DB db = mongo.getDB("ecommerce");
	DBCollection col = db.getCollection("products");
	return new PageResult(col.find(), range.getFromIndex(),
			range.getToIndex());
}