Spring Data mongo to insert null values to DB

百般思念 提交于 2019-12-03 15:57:56

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}*
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!