alegria
alegria

Reputation: 1482

Adding a new field with default value in a collection in Spring Data MongoDB

I am adding a new boolean field in a collection by adding an attribute to a Java Class entity that is being used in the MongoRepository interface. However, the existing documents' new field is being initialised as null in the database. I want the new field's default value in existing documents to be set to false. How can this be done in Spring Data MongoDB?

Upvotes: 2

Views: 4164

Answers (1)

Dwaraka
Dwaraka

Reputation: 179

Let say your version 1 Java entity was

@Document
Public Class Person {
@Id
Private String id;
private String firstName;
private String lastName;
.........
.........

And later you have introduced

@Document
Public Class Person {
@Id
Private String id;
private String firstName;
private String lastName;
private Boolean isAlive; //New Boolean attribute
.........
.........

In java the default value of an instance object is null and so a document in mongoDB with no value for isAlive will be defaulted to null. If you need the default value to be false you could do this

private Boolean isAlive = Boolean.FALSE;

Upvotes: 1

Related Questions