MongoDB的Spring Data是否允许带有可选字段的文档?

时间:2016-10-13 00:24:29

标签: spring mongodb spring-data spring-data-mongodb

我可以拥有一个可以为空的字段: - 如果其值为null,我们不会在文档中存储字段(名称或值),并且 - 如果其值为非null,我们将在其上存储字段名称和值。

1 个答案:

答案 0 :(得分:4)

是的,确实如此,只是在创建模型时不设置属性,该字段和值不会插入到mongodb文档中。设置值的字段,只有那些将存储在mongodb文档中。

package org.scalar.test;

import org.scalar.model.Product;
import org.scalar.model.Summary;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.mongodb.core.MongoTemplate;

public class App {

    public static void main(String[] args) {

        ApplicationContext context = new ClassPathXmlApplicationContext("spring/applicationContext.xml");

        for (int i=0;i<10;i++) {
                Product product = new Product();
                product.setId(String.valueOf(i));
                /*Summary summary = new Summary(); */

                MongoTemplate template = (MongoTemplate)context.getBean("mongoTemplate");

                template.save(product);

        }       

        System.out.println("end");
        ((ClassPathXmlApplicationContext)context).close();


    }

}

Product.java

package org.scalar.model;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection="products")
public class Product {

    @Id
    public String id;
    public Summary summary;

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public Summary getSummary() {
        return summary;
    }
    public void setSummary(Summary summary) {
        this.summary = summary;
    }


}

Mongodb输出

> db.products.find();
{ "_id" : "0", "_class" : "org.scalar.model.Product" }
{ "_id" : "1", "_class" : "org.scalar.model.Product" }
{ "_id" : "2", "_class" : "org.scalar.model.Product" }
{ "_id" : "3", "_class" : "org.scalar.model.Product" }
{ "_id" : "4", "_class" : "org.scalar.model.Product" }
{ "_id" : "5", "_class" : "org.scalar.model.Product" }
{ "_id" : "6", "_class" : "org.scalar.model.Product" }
{ "_id" : "7", "_class" : "org.scalar.model.Product" }
{ "_id" : "8", "_class" : "org.scalar.model.Product" }
{ "_id" : "9", "_class" : "org.scalar.model.Product" }

HTH