spring-projects / spring-data-mongodb

Provides support to increase developer productivity in Java when using MongoDB. Uses familiar Spring concepts such as a template classes for core API usage and lightweight repository style data access.
https://spring.io/projects/spring-data-mongodb/
Apache License 2.0
1.62k stars 1.09k forks source link

Add support for MongoDB backed counters. #4823

Open christophstrobl opened 4 weeks ago

christophstrobl commented 4 weeks ago

The goal of this issue is to help users manage server side counters more easily.

We could leverage findAndUpdate that issues an update with $inc, upsert and ReturnDocument.AFTER to maintain a counter document in a specific collection obtaining the incremented value as outlined below.

return mongoTemplate.execute("sequence_collection", collection -> {
    return collection.findOneAndUpdate(new Document("_id", sequenceName), new Document("$inc", new Document("count", 1)), new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER)).getLong("count");
});

Wrapping the above in something like a MongoSequence would allow easy access. This issue is somehow related to #1842 which IMO should be addressed on a broader basis in data-commons.