Spring Data - MongoDB索引DBRef [英] Spring Data - MongoDB indexing DBRef

查看:564
本文介绍了Spring Data - MongoDB索引DBRef的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用spring-data-mongodb-1.2.0.RELEASE。
我有两个A和B类,其中B有一个A的引用,它用@DBRef注释。

I'm using spring-data-mongodb-1.2.0.RELEASE. I have two classes A and B where B has a reference to A and it is annotated with @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;
}
}

因为我正在查询B的所有实例引用某个A:

Since I'm quering for all instances of B that are refering to a certain A:

B fromDB = mongoOperations.findOne(Query.query(Criteria.where("a.$id").is(a1.id)), B.class);

我需要将其编入索引。

首次将B实例插入MongoDB后,应创建一个索引。
从下面可以看出它不是:

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

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

Does anyone know how can I create such an index ?

此外,它看起来像DBRef字段(可以看到mongo shell)与
中定义的格式不匹配 MongoDB文档

In addition it looks like the DBRef filed (as can be seen by the mongo shell) does not match to the format as it is defined at MongoDB documentation.

我在这里遗漏了什么吗?

Am I missing something here?

推荐答案

您可以使用mongo shell创建索引,但如果您想通过代码执行此操作,并且因为您使用的是spring-data-mongodb,请使用:

You can create the index with the mongo shell, but if you want to do it through code and since you are using spring-data-mongodb, use this:

mongoTemplate.indexOps(B.class).ensureIndex(new index()。on(a,Order.ASCENDING));

如果您的班级名称与集合名称不匹配,您也可以指定集合的​​名称:

You can also specify the name of the collection if the name of your class doesn't match it:

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

这篇关于Spring Data - MongoDB索引DBRef的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆