Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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}})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading