DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • How to Introduce a New API Quickly Using Micronaut
  • How to Merge HTML Documents in Java
  • Designing a Java Connector for Software Integrations
  • Jakarta NoSQL 1.0: A Way To Bring Java and NoSQL Together

Trending

  • Introduction to Retrieval Augmented Generation (RAG)
  • Security by Design: Building Full-Stack Applications With DevSecOps
  • IoT and Cybersecurity: Addressing Data Privacy and Security Challenges
  • How GitHub Copilot Helps You Write More Secure Code
  1. DZone
  2. Data Engineering
  3. Databases
  4. MongoDB Java API: Using a Sequence Collection With FindAndModify()

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?

By 
Kevin Hooke user avatar
Kevin Hooke
·
Jul. 06, 16 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
10.2K Views

Join the DZone community and get the full member experience.

Join For Free

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. here, here, 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");
}
API MongoDB Java (programming language)

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

Opinions expressed by DZone contributors are their own.

Related

  • How to Introduce a New API Quickly Using Micronaut
  • How to Merge HTML Documents in Java
  • Designing a Java Connector for Software Integrations
  • Jakarta NoSQL 1.0: A Way To Bring Java and NoSQL Together

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!