Over a million developers have joined DZone.

MongoDB Java API: Using a Sequence Collection With FindAndModify()

Documents in MongoDB have a unique object ID when they are created. How can we get around this to develop a more effective REST API when document lookups are involved?

· Database Zone

Build fast, scale big with MongoDB Atlas, a hosted service for the leading NoSQL database. Try it now! Brought to you in partnership with MongoDB.

MongoDB doesn't have an equivalent of sequences typically used in relational databases — documents are automatically given a unique ObjectId value for the "_id" property when inserted.

To return data from documents via a REST API, it may be more useful to use a sequential unique key. The MongoDB docs have an example of how you could use a collection to hold a document per sequence that you need  and increment a value property each time you retrieve it with findAndModify().

There are a number of questions on StackOverflow related to this approach. Most seem related to the approach doc linked above (e.g. herehere, and articles elsewhere, like here).

To implement this approach using the Java API, using findAndModify() seems to be key, as you need to ensure you are querying and incrementing the sequence value in a document in a single, atomic step. After that point, once you have the updated/next value from your document holding your sequence, the fact that you use that value in a subsequent atomic insert to another document seems to be safe (please leave me a comment if this assumption is not correct!), as every call to findAndModify() to increment the sequence value is atomic (making an assumption here based on my limited MongoDB knowledge, but I think this is correct!).

Here’s how I implemented the approach using the Java API:

public int getNextSequence() throws Exception {
    DB db = MongoConnection.getMongoDB();

    DBCollection sequences = db.getCollection("sequences");

    // fields to return
    DBObject fields = BasicDBObjectBuilder.start()
        .append("_id", 1)
        .append("value", 1).get();

    DBObject result = sequences.findAndModify(
      new BasicDBObject("_id", "addressId"), //query 
      fields, // what fields to return
      null, // no sorting
      false, //we don't remove selected document
      new BasicDBObject("$inc", new BasicDBObject("value", 1)), //increment value
      true, //true = return modified document
      true); //true = upsert, insert if no matching document

      return (int)result.get("value");

Now it's easier than ever to get started with MongoDB, the database that allows startups and enterprises alike to rapidly build planet-scale apps. Introducing MongoDB Atlas, the official hosted service for the database on AWS. Try it now! Brought to you in partnership with MongoDB.


Published at DZone with permission of Kevin Hooke, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}