在正确的集合中创建索引 [英] Create index in correct collection

查看:39
本文介绍了在正确的集合中创建索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用@Index(unique = true) 注释一个文档,如下所示:

I annotate a document with @Index(unique = true) like so:

public class ADocumentWithUniqueIndex {
    private static final long serialVersionUID = 1L;

    @Indexed(unique = true)
    private String iAmUnique;

    public String getiAmUnique() {
        return iAmUnique;
    }

    public void setiAmUnique(String iAmUnique) {
        this.iAmUnique = iAmUnique;
    }
}

保存对象时,我指定了一个自定义集合:

When saving the object, I specify a custom collection:

MongoOperations mongoDb = ...

mongoDb.save(document, "MyCollection");

结果我得到:

  • MyCollection"中的新文档
  • ADocumentWithUniqueIndex"集合中的索引

如何在MyCollection"中创建索引而不必在注释中明确指定?

How can I create the index in "MyCollection" instead without having to explicitly specify it in the annotation?

背景:

  • 在我们的用例中,默认集合名称过于模糊.我们不能保证不会有两个同名但在不同包中的文档.所以我们将包名称添加到集合中.
  • 将文档映射到集合是在基础架构组件中处理的.
  • 集合名称等实现细节不应泄漏到单个文档中.
  • 我知道这有点抽象之上的抽象"的味道,但这是必需的,因为我们必须支持 MongoDb 和 Windows Azure blob 存储.不过现在不行了...

这似乎是在基础设施组件中隐藏持久性细节的相当标准的方法.对此方法的任何评论也表示赞赏.

This seemed like a fairly standard approach to hide the persistence details in a infrastructure component. Any comments on the approach appreciated as well.

推荐答案

定义要存储的对象的集合然后期望索引注释起作用是一种不寻常的做法.这里有几个选项:

It's kind of unusual to define the collection for an object to be stored and then expect the index annotations to work. There's a few options you have here:

  1. ADocumentWithUniqueIndex 上使用 @Document 并手动配置集合名称.这当然会导致该类的所有对象都被持久化到该集合中.

  1. Use @Document on ADocumentWithUniqueIndex and configure the collection name manually. This will cause all objects of that class to be persisted into that collection of course.

通过 MongoOperations.indexOps() 手动创建索引到您要使用的集合中.这将更符合您在持久性操作期间手动确定集合名称的方法.

Manually create indexes via MongoOperations.indexOps() into the collections you'd like to use. This would be more consistent to your approach of manually determining the collection name during persistence operations.

这篇关于在正确的集合中创建索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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