我使用spring-data-mongodb-1.2.0.RELEASE,我有两个类A和B,其中B引用了A,并用@DBRef进行了注释。
A类:
@Document(collection = "a")
public class A {
@Id
public String id;
/** The TicketGrantingTicket this is associated with. */
@Field
public String name;
public A(String id, String name) {
this.id = id;
this.name = name;
}
}B类:
@Document(collection = "b")
public class B {
@Id
public String id;
@Field
public String name;
@DBRef
@Indexed
public A a;
public B(String id, String name, A a) {
super();
this.id = id;
this.name = name;
this.a = a;
}
}因为我要查询引用某个A的B的所有实例:
B fromDB = mongoOperations.findOne(Query.query(Criteria.where("a.$id").is(a1.id)), B.class);我需要它被编入索引。
在第一次将B实例插入MongoDB之后,应该创建一个索引。如下所示,它不是这样的:

有人知道如何创建这样的索引吗?
此外,看起来DBRef文件(可以从mongo shell中看到)与MongoDB documentation中定义的格式不匹配。
我是不是漏掉了什么?
发布于 2013-04-05 04:22:16
您可以使用mongo shell创建索引,但如果您想通过代码来创建索引,并且由于您使用的是spring-data-mongodb,请使用以下命令:
mongoTemplate.indexOps(B.class).ensureIndex(new Index().on("a", Order.ASCENDING));
如果类的名称与集合名称不匹配,还可以指定集合的名称:
mongoTemplate.indexOps("b").ensureIndex(new Index().on("a", Order.ASCENDING));发布于 2013-04-05 02:36:39
我认为这会起作用的:@CompoundIndex(name = "b_ref_to_a", def = "{'a.id' : 1}") @Document(collection = "b") public class B {...}
如果不是这样,您可以在带有@PostConstruct注释的方法中调用mongoTemplate.indexOps("b").ensureIndex(...)
发布于 2014-09-29 00:13:07
我也遇到了同样的问题,对我来说,orid的解决方案可以工作,但我必须将@CompoundIndex包装在一个@CompoundIndexes中,否则它就不能工作(我使用的是Spring Roo)。
@CompoundIndexes({
@CompoundIndex(name = "b_ref_to_a", def = "{'a.id' : 1}")
})
@Document(collection = "b")
public class B {...}https://stackoverflow.com/questions/15818619
复制相似问题