Spring数据-MongoDB索引DBRef

Spring数据-MongoDB索引DBRef,mongodb,indexing,spring-data-mongodb,dbref,Mongodb,Indexing,Spring Data Mongodb,Dbref,我使用的是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

我使用的是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);
我需要把它编入索引

在MongoDB中首次插入B实例之后,应该创建索引。 从下面可以看出,它没有:

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

此外,看起来DBRef字段(可以通过mongo shell看到)与在中定义的格式不匹配

我在这里遗漏了什么吗?

我想这会有用的:
@compoundex(name=“b_ref_to_a”,def=“{'a.id':1}”)
@文件(收集=“b”)
公共B类{…}


如果没有,您可以在用
@PostConstruct
注释的方法中调用
mongoTemplate.indexOps(“b”).ensureIndex(…)
,也可以使用mongo shell创建索引,但是如果您想通过代码来创建索引,并且由于您使用的是spring data mongodb,请使用以下方法:

mongoTemplate.indexOps(B.class).ensureIndex(新索引().on(“a”,Order.升序))

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

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

我也遇到了同样的问题,对我来说orid的解决方案是有效的,但我必须将@CompoundIndex包装在@CompoundIndex中,否则它就不起作用了(我使用的是SpringRoo)


谢谢你的帮助。尽管如此,为什么不创建索引,尽管它是用@index注释的呢?另一个悬而未决的问题是,为什么MongoDB文档以不同于Mongo shell快照的格式显示DBRef?对于@Indexed,它并没有真正的文档化,但我认为它不适合复杂类型,无论如何,对我来说从来都不起作用。就我个人而言,我使用上面提到的两种方法之一来索引“complex”类型。至于第二个问题,您使用的是什么版本的mongodb shell?试试
db.d.find({},{“a$ref”:1,“a$id”:1})
你得到了什么?我使用的是Mongo db和shell版本2.4.1。我能够执行下一个查询:db.b.find({“a$id”:},{“a$id”:1})和db.b.find({“a$id”:},{“a$ref”:1}),但我不能在投影参数中包含a$ref和a$id,条件参数必须包含“a$id”。最重要的是,为了使用在“a”上创建的索引,查询元素必须包括a.$id和a.$ref:db.b.find({a:{“$ref”:a,$id:})
@CompoundIndexes({
    @CompoundIndex(name = "b_ref_to_a", def = "{'a.id' : 1}")
})
@Document(collection = "b")
public class B {...}
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();