Spring Data - MongoDB 索引 DBRef

2024-05-27

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

Class 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;
}
}

Class 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);

我需要将其编入索引。

After the first insertion of a B instance into MongoDB an index should be created. As can be seen below it doesn't:

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

此外,看起来 DBRef 归档(如 mongo shell 所示)与定义的格式不匹配MongoDB 文档 http://docs.mongodb.org/manual/applications/database-references/#format.

我在这里错过了什么吗?


您可以使用 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));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring Data - MongoDB 索引 DBRef 的相关文章

随机推荐