首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring Data - MongoDB索引DBRef

Spring Data - MongoDB索引DBRef
EN

Stack Overflow用户
提问于 2013-04-05 02:11:57
回答 4查看 10.1K关注 0票数 10

我使用spring-data-mongodb-1.2.0.RELEASE,我有两个类A和B,其中B引用了A,并用@DBRef进行了注释。

A类:

代码语言:javascript
复制
@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类:

代码语言:javascript
复制
@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的所有实例:

代码语言:javascript
复制
B fromDB = mongoOperations.findOne(Query.query(Criteria.where("a.$id").is(a1.id)), B.class);

我需要它被编入索引。

在第一次将B实例插入MongoDB之后,应该创建一个索引。如下所示,它不是这样的:

有人知道如何创建这样的索引吗?

此外,看起来DBRef文件(可以从mongo shell中看到)与MongoDB documentation中定义的格式不匹配。

我是不是漏掉了什么?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2013-04-05 04:22:16

您可以使用mongo shell创建索引,但如果您想通过代码来创建索引,并且由于您使用的是spring-data-mongodb,请使用以下命令:

mongoTemplate.indexOps(B.class).ensureIndex(new Index().on("a", Order.ASCENDING));

如果类的名称与集合名称不匹配,还可以指定集合的名称:

代码语言:javascript
复制
mongoTemplate.indexOps("b").ensureIndex(new Index().on("a", Order.ASCENDING));
票数 9
EN

Stack Overflow用户

发布于 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(...)

票数 5
EN

Stack Overflow用户

发布于 2014-09-29 00:13:07

我也遇到了同样的问题,对我来说,orid的解决方案可以工作,但我必须将@CompoundIndex包装在一个@CompoundIndexes中,否则它就不能工作(我使用的是Spring Roo)。

代码语言:javascript
复制
@CompoundIndexes({
    @CompoundIndex(name = "b_ref_to_a", def = "{'a.id' : 1}")
})
@Document(collection = "b")
public class B {...}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15818619

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档