javaspringmongodbspring-bootmongotemplate

How can I update priority list after deleting a record in MongoDB using Spring Boot?


I have a Spring Boot application connected to a MongoDB. In the MongoDB I have a collections called configurations with the following documents:

_id: ObjectId('6231984016d57c64884c8e52')
name: Gio
priority: 1

_id: ObjectId('61f2a0351a7b18283fc5ce9b')
name: Blamee
priority: 2

_id: ObjectId('61f39f8ae2daa732deff6d90')
name: Lonic
priority: 3

_id: ObjectId('61e56339b528bf009feca149')
name: TechRaz
priority: 4

_id: ObjectId('62013a86b6b62621b529bed4')
name: Gild
priority: 5

All the documents have a unique priority. From the user interface you can change the priority from a list where you can drag and drop the configs to the priority you wish. However the issue I have is that when a configuration is deleted (you can only delete one configuration at a time), a hole is created in the priority index. I want to know how I can make some code that closes the priority gap when a config is deleted, so if "Lonic" is deleted I want the priorities to change like this:

_id: ObjectId('6231984016d57c64884c8e52')
name: Gio
priority: 1

_id: ObjectId('61f2a0351a7b18283fc5ce9b')
name: Blamee
priority: 2

_id: ObjectId('61e56339b528bf009feca149')
name: TechRaz
priority: 3

_id: ObjectId('62013a86b6b62621b529bed4')
name: Gild
priority: 4

This is what I've tried:

After deleting the configuration I say:

Query query = new Query();
query.with(Sort.by(Sort.Direction.asc, "priority"));
List<Configuration> remainingConfigsAfterDelete =  mongoTemplate.find(query, Configuration.class);

for (int i = 1; i+1 < remainingConfigsAfterDelete.size(); i++) {
    remainingConfigsAfterDelete.get(i).setPriority(i);
}

And then somehow update all the priorities using bulkOperations or something. The first priority has to start at 1 not 0. I just feel like I'm overdoing it here. There gotta be an easier way to do this.


Solution

  • When a priority is deleted, every priority greater than that should be decremented.

    db.collection.updateMany({priority: {$gt: deletedPriority}},{$inc: {priority: -1}})