首页 > 解决方案 > 为什么 MongoDB.Driver Indexes.CreateOne 无法创建索引并出现错误“命令 createIndexes failed”?

问题描述

通过代码创建新集合时,添加新索引的调用失败:

private static void CreateCollection<T>(string collectionName, CreateIndexModel<T> index)
{
  var database = GetMongoDatabase();

  database.CreateCollection(collectionName);

  var collection = database.GetCollection<T>(collectionName);
  collection.Indexes.CreateOne(index); // Message=Command createIndexes failed
}

标签: c#mongodbmongodb.driver

解决方案


在添加索引之前,您需要等待异步集合创建:

private static async Task CreateCollection<T>(string collectionName, CreateIndexModel<T> index)
{
  var database = GetMongoDatabase();

  await database.CreateCollectionAsync(collectionName);

  var collection = database.GetCollection<T>(collectionName);
  collection.Indexes.CreateOne(index);
}

推荐阅读