具有唯一索引的嵌套对象

时间:2016-03-23 11:13:27

标签: spring mongodb

我刚刚从mongo 2.0.6做了3.2,并注意到unique-index现在也用于嵌套对象。 有没有办法告诉mongo防止嵌套对象的唯一索引?

我声明嵌套对象的索引,如@Indexed(unique = true)

Spring版本:4.2.5.RELEASE

Spring-data-mongodb版本:1.8.4.RELEASE

Mongo-driver版本:mongo-java-driver 3.2.2

我的代码:

package jobs;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "jobs")
public class Job {

private String title;
private CityInfo cityInfo;

// getter/setter
public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public CityInfo getCityInfo() {
    return cityInfo;
}

public void setCityInfo(CityInfo cityInfo) {
    this.cityInfo = cityInfo;
}
}

package jobs;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "city_infos")
public class CityInfo {

@Indexed(unique = true)
private String cityName;

// getter/setter
public String getCityName() {
    return cityName;
}

public void setCityName(String cityName) {
    this.cityName = cityName;
}
}


package jobs;
import org.springframework.data.mongodb.core.MongoOperations;
public class JobMain {

public static void main(String[] args) {
    MongoOperations mongo = MongoPoolingUtils.getCentralTemplate();
    CityInfo cityInfo = new CityInfo();
    cityInfo.setCityName("Berlin");
    Job job1 = new Job();
    job1.setTitle("java coder");
    job1.setCityInfo(cityInfo);
    Job job2 = new Job();
    job2.setTitle("php coder");
    job2.setCityInfo(cityInfo);
    mongo.save(job1);
    mongo.save(job2);
}
}

只有1个作业保存到数据库中。

0 个答案:

没有答案