ETag Object in MongoDB Document - Java Driver

My Java application has a REST GET apis (implemented with JAX-RS) accessing MongoDB collection. I am trying to implement a web cache to improve response times (by reducing document reading on the MongoDB side).

I'm looking for a standard way to provide ETag ( ) for resources (resources are sourced from documents in MongoDB collection) so that ETag in MongoDB collection is automatically updated every time the document is updated.

Now I can check ETag in HTTP request ("If-None-Match") with ETag in MongoDB document and if both are equal with return 304 (Not Modified). Now WebCache can return the already cached resource to the client, which will improve the response time.

While googling, I got the following 2 options:

  • hascode () as ETag: get document from MongoDB and populate Java object, then compute hashCode () which is used as ETag. But I want to avoid this overhead (full doc read + hashcode calculation)

  • Last Modified Date as ETag: Add a new Last Modified field to the mongoDB collection.   This mechanism is more suitable for the "Last Modified" (HTTP) response header). It looks like the date is being misused here for ETag. Here I have to modify an existing document to insert a new field (updatedTime). Once again, the HTML date precision is sec and the mongoDB date is msec.

Please provide a standard way to expose ETag to MongoDB.


source to share

1 answer

I am doing a hash computation before transferring the object to MongoDB by storing it in a field etag


On request, I can find {"_id": REQUESTED_ID, "etag": {$ne: RECEIVED_ETAG}}


If no document is returned, you still need to find out if the document exists {"_id": REQUESTED_ID}

(I know, but perhaps in your case WebCache can handle this and return 404, otherwise 304).

If it returns a document, just use its attribute etag

to populate the header etag

and possibly remove it from the returned body.



All Articles