Mod*_*odi 10 indexing mongodb dbref spring-data-mongodb
我正在使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
因为我正在查询所有引用某个A的B实例:
B fromDB = mongoOperations.findOne(Query.query(Criteria.where("a.$id").is(a1.id)), B.class);
Run Code Online (Sandbox Code Playgroud)
我需要它被索引.
在第一次将B实例插入MongoDB之后,应该创建一个索引.从下面可以看出它没有:

有谁知道如何创建这样的索引?
此外,它看起来像DBRef字段(可以通过mongo shell看到)与MongoDB文档中定义的格式不匹配 .
我在这里错过了什么吗?
您可以使用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));
Run Code Online (Sandbox Code Playgroud)
我认为这会奏效:
@CompoundIndex(name = "b_ref_to_a", def = "{'a.id' : 1}")
@Document(collection = "b")
public class B {...}
如果没有,您可以调用mongoTemplate.indexOps("b").ensureIndex(...)带有@PostConstruct或带有注释的方法
| 归档时间: |
|
| 查看次数: |
8996 次 |
| 最近记录: |