Spring Data - MongoDB索引DBRef

11
我可以翻译成中文。这段内容是关于编程的,讲解了使用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文档中定义的格式不匹配。
我是否漏掉了什么?
4个回答

9

您可以使用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));

5
我认为这个会起作用: @CompoundIndex(name = "b_ref_to_a", def = "{'a.id' : 1}") @Document(collection = "b") public class B {...} 如果不行,你可以在一个使用@PostConstruct注解的方法中调用mongoTemplate.indexOps("b").ensureIndex(...)

1
感谢您的帮助。但是,为什么索引没有被创建,尽管它已经用@Indexed进行了注释?另一个未解决的问题是,为什么MongoDB文档显示的DBRef格式与在Mongo shell快照中看到的格式不同。 - Modi
关于@Indexed,它并没有真正的文档,但我认为它不适用于复杂类型,反正对我来说从未奏效。个人而言,我使用上述两种方法之一来索引“复杂”类型。至于第二个问题,您使用的是哪个版本的mongodb shell?尝试db.d.find({},{"a.$ref" : 1, "a.$id" : 1}),您得到了什么? - Ori Dar
我正在使用Mongo DB和shell版本2.4.1。我能够执行以下查询:db.b.find({"a.$id":<val>},{"a.$id":1})和db.b.find({"a.$id":<val>},{"a.$ref":1}),但是不能在投影参数中包含a.$ref和a.$id,条件参数必须包括"a.$id" 。最重要的是,为了使用在'a'上创建的索引,查询元素必须包括a.$id和a.$ref:db.b.find({a:{"$ ref":a,"$ id":<val>}})。 - Modi

3

我曾经遇到过同样的问题,对我来说,orid的解决方案有效,但我必须将@CompoundIndex包装在@CompoundIndexes中,否则它不起作用(我正在使用Spring Roo)。

@CompoundIndexes({
    @CompoundIndex(name = "b_ref_to_a", def = "{'a.id' : 1}")
})
@Document(collection = "b")
public class B {...}

1
DBObject indexOptions = new BasicDBObject();
indexOptions.put("a", 1);
indexOptions.put("b", 1);
indexOptions.put("c.d", 1);
indexOptions.put("e.f", 1);
CompoundIndexDefinition indexDefinition =
            new CompoundIndexDefinition(indexOptions);
mongoTemplate.indexOps(.class).ensureIndex(indexDefinition);

for unique index you can add mongoTemplate.indexOps(.class).ensureIndex(indexDefinition).unique();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接