9

I am using Spring data mongo to insert a record to Mongo,

here is my code mongoTemplate.save(person,"personCollection");

Here is my person object

public class Person implements Serializable {
   int age;
   String address;
   String name;

//Getters and setters including hashcode and equals
}

my address is null here , after inserting the record in the collection, the data is populated with only age and name

i know that mongodb treats null value and noKey as the same thing, but my requirement is to even populate the address:null to have the schema consistent how do i do this with Spring Data mongo

current o/p: {"age":21,"name":"john Doe"}

expected o/p: {"age":21,"name":"john Doe","address":null}

  • I'm afraid that is not possible. here is the relavant jira. https://jira.spring.io/browse/DATAMONGO-1107. you may want to look into storing some value as default instead. – s7vr Dec 13 '16 at 02:38

2 Answers2

7

NoSQL DB works in a different way compared to RDBMS. the document {"age":21,"name":"john Doe"} is same as {"age":21,"name":"john Doe";"address":null}

instead of storing the key's as null better to not store the key at all this improves the performance of your reads/updates against the DB. However, if your usecase still demands to sore null due to whatever the reasons it might be convert your POJO to BSONObject and then persist the BSONObject in the MongoDB.

Here is the example ( but however it will be only a work around to get the things going)

BSONObject personBsonObj = BasicDBObjectBuilder.start()
                .add("name","John Doe")
                .add("age",21)
                .add("address",null).get();


 if you are using spring data mongo use

mongoTemplate.insert(personBsonObj,"personCollection");
document in the db:
db.personCollection.findOne().pretty();
{"age":21,"name":"John Doe";"address":null}*
  • Could you please guide me here : https://stackoverflow.com/questions/55604660/caused-by-org-bson-codecs-configuration-codecconfigurationexception-cant-find ? –  Apr 10 '19 at 05:33
  • How to do the same for nested objects? Let' say I want to add Person Object (which has firstName, lastName, address etc ..) example .add("person", person) – Mallu Golageri Apr 04 '21 at 18:16
0

I've solved this problem using the below code

final Document document = new Document();
document.put("test1", "test1");
document.put("test2", null);
document.put("test3", "test3");
mongoTemplate.getCollection("your-collection-name").insert(document);

Here instead of using BSONObject, I used Document object and it worked fine.

Document inserted in DB

{
    "_id" : ObjectId("some-id"),
    "test1" : "test1",
    "test2" : null,
    "test3" : "test3"
}
Abhilash
  • 457
  • 5
  • 9