Search code examples
springmongodbspring-bootkotlinspring-data

best way to add new properties to a model when using spring boot with mongodb


I'm looking for a better way to change a model with Spring + Mongodb, currently every time a property is added to a model, we have to create a command to be ran in mongosh to add that field to all documents, and then save it so that it can be ran on every environment that the new model is pushed to.

So for example, lets say a Event object has the properties:

@Document
data class Device(
    @Id
    val id: String? = null,
    @Indexed(unique = true)
    val name: String,
    var location: String,
)

And we want to add a field "date": 2023-02-02T20:10:19.111Z to it. Currently I will have to create a mongosh command to update all events on the collection to add that field, so something like this:

db.device.updateMany({}, {$set: {'date': new Date().toISOString()}})

We then save this, and remember to run it every single time we merge to a upstream branch.

Is there a better way to define a new model with the date, so that it can create the field automatically?


Solution

  • I would add the new property with a default value, but everyone usecase/trade-offs is different.

    @Document
    data class Device(
        @Id
        val id: String? = null,
        @Indexed(unique = true)
        val name: String,
        var location: String,
        val newProperty:String? = null
    )
    

    This will allow you to get values don't exist in the database as null