我正在使用Spring数据mongo向Mongo中插入一条记录,
I am using Spring data mongo to insert a record to Mongo,
这是我的代码 mongoTemplate.save(person,"personCollection");
here is my code mongoTemplate.save(person,"personCollection");
这是我的人对象
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
我知道mongodb将null值和noKey视为同一个东西,但是我的要求是甚至填充address:null以使架构保持一致,我该如何使用Spring Data mongo做到这一点
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
当前o/p:{"age":21,"name":"john Doe"}
current o/p: {"age":21,"name":"john Doe"}
预期的o/p:{"age":21,"name":"john Doe","address":null}
expected o/p: {"age":21,"name":"john Doe","address":null}
推荐答案NoSQL DB与RDBMS的工作方式不同. 文档{"age":21,"name":"john Doe"}与{"age":21,"name":"john Doe";"address":null}
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}
最好不要完全存储密钥,而不是将密钥存储为null,这样可以提高对数据库的读取/更新的性能. 但是,如果您的用例由于任何原因仍然需要痛哭null,则可能会将POJO转换为BSONObject,然后将BSONObject保留在MongoDB中.
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}*更多推荐
Spring Data mongo将空值插入数据库
发布评论