【问题标题】:Why does MongoDB.Driver Indexes.CreateOne fail to create Index with error "Command createIndexes failed"?为什么 MongoDB.Driver Indexes.CreateOne 无法创建索引并出现错误“命令 createIndexes failed”?
【发布时间】:2020-06-24 16:36:47
【问题描述】:

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

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# mongodb mongodb.driver


    【解决方案1】:

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

    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);
    }
    

    【讨论】:

    • 或者直接忽略对CreateCollection的调用,因为当您创建索引时节点会隐式执行此操作。
    猜你喜欢
    • 1970-01-01
    • 2016-06-04
    • 1970-01-01
    • 2015-12-21
    • 2017-04-24
    • 2020-04-18
    • 2019-09-28
    • 1970-01-01
    • 2021-12-17
    相关资源
    最近更新 更多