我正在使用 Spring data mongo 向 Mongo 中插入一条记录,
这是我的代码 mongoTemplate.save(person,"personCollection");
这是我的人物对象
public class Person implements Serializable {
int age;
String address;
String name;
//Getters and setters including hashcode and equals
}
我的地址在这里是空的,在集合中插入记录后,数据只填充了年龄和名字
我知道 mongodb 将 null 值和 noKey 视为同一事物,但我的要求是甚至填充地址:null 以使模式一致我如何使用 Spring Data mongo 做到这一点
当前职业:{"age":21,"name":"john Doe"}
预计 o/p:{"age":21,"name":"john Doe","address":null}
最佳答案
与 RDBMS 相比,NoSQL DB 的工作方式不同。 文档 {"age":21,"name":"john Doe"} 与 {"age":21,"name":"john Doe";"address":null} 相同
与其将 key 存储为 null 不如根本不存储 key ,这会提高您对数据库的读取/更新性能。 但是,如果您的用例由于任何原因仍然需要处理 null,则可能会将您的 POJO 转换为 BSONObject,然后将 BSONObject 保留在 MongoDB 中。
这是示例(但它只是解决问题的方法)
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}*
关于java - Spring Data mongo 将空值插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41112607/