简体   繁体   English

Spring Data mongo 向 DB 插入空值

[英]Spring Data mongo to insert null values to DB

I am using Spring data mongo to insert a record to Mongo,我正在使用 Spring data mongo 向 Mongo 插入一条记录,

here is my code mongoTemplate.save(person,"personCollection");这是我的代码 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我知道 mongodb 将 null 值和 noKey 视为同一件事,但我的要求是甚至填充 address:null 以使架构一致我如何使用 Spring Data mongo 执行此操作

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

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

NoSQL DB works in a different way compared to RDBMS.与 RDBMS 相比,NoSQL DB 的工作方式不同。 the document {"age":21,"name":"john Doe"} is same as {"age":21,"name":"john Doe";"address":null}文档 {"age":21,"name":"john Doe"} 与 {"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.而不是将密钥存储为 null 更好地不存储密钥,这可以提高您对数据库的读取/更新的性能。 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.但是,如果您的用例由于任何原因仍然要求使用 null,则可能会将您的 POJO 转换为 BSONObject,然后将 BSONObject 保留在 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}*

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.在这里,我没有使用 BSONObject,而是使用了 Document 对象,它运行良好。

Document inserted in DB插入数据库的文档

{
    "_id" : ObjectId("some-id"),
    "test1" : "test1",
    "test2" : null,
    "test3" : "test3"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM