Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
643 views
in Technique[技术] by (71.8m points)

java - Spring Data mongo to insert null values to DB

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}

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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}*

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...