Java 是否可以在createCollection com.mongoDB.client.MongoDatabase.createCollection期间在mongoDB上创建索引(

Java 是否可以在createCollection com.mongoDB.client.MongoDatabase.createCollection期间在mongoDB上创建索引(,java,mongodb,Java,Mongodb,我正在Java中使用com.mongodb.client.MongoDatabase。我想使用MongoDatabase.createCollection(…)创建一个索引为的新集合 我目前的执行情况: mongoDatabase.createCollection("employees"); mongoDatabase.getCollection("employees") .createIndex(Indexes.ascending("

我正在Java中使用com.mongodb.client.MongoDatabase。我想使用MongoDatabase.createCollection(…)创建一个索引为的新集合

我目前的执行情况:

mongoDatabase.createCollection("employees");
mongoDatabase.getCollection("employees")
     .createIndex(Indexes.ascending("empId"), new IndexOptions().unique(true));

有可能将上面的两条语句合并为一条吗?

我不知道在一个API调用中实现这两条语句的方法。但是,有没有什么特别的原因可以让它们在一个方法调用中实现?可能这部分代码对事务性问题(如创建集合)不太敏感但索引创建失败了

如果将Mongo 4+与Spring Mongo库一起使用,则可以将这两条语句放在一个方法中,然后使用
@Transactional
对其进行注释:

@Transactional
public void createCollectionAndIndex(){
mongoDatabase.createCollection(“员工”);
mongoDatabase.getCollection(“员工”)
.createIndex(index.升序(“empId”),新的IndexOptions().unique(true));
}

然后,要么所有逻辑都成功,要么发生一些异常并回滚所有内容。

在不存在的集合上创建索引时,该命令还会创建一个空集合和索引。我也在
mongo
shell中验证了它

mongoDatabase.getCollection("employees")
     .createIndex(Indexes.ascending("empId"), new IndexOptions().unique(true));

// or

employeeCollection.createIndex(Indexes.ascending("empId"), new IndexOptions().unique(true));

当您创建索引时,它也会创建集合(如果集合不存在)。是这样吗,您的意思是说mongoDatabase.createCollection(“employees”);不是必需的语句?只需
mongoDatabase.getCollection(“employees”).createIndex(…)
。不需要
创建集合
-除非您喜欢使用@prasad\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu。