c# - 为什么 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
}
解决方案
在添加索引之前,您需要等待异步集合创建:
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);
}
推荐阅读
- r - 如何在 R studio 的概率图中添加一个显示条件变量分布的图层?
- azure - 直到 Azure 数据工厂中的活动在条件不匹配时执行
- php - 如何从 MySQL 数据库表列值中删除特殊字符?
- python - 类型错误:Jupyter 笔记本
- c++ - 一维动态数组,括号
- javascript - 如何在Javascript中将两位数字符串转换为int?
- python - 为什么命令 python manage.py runserver 不起作用?
- snmp - 是否有用于通过 SNMP 进行通信的设备的通用对象标识符?
- angular - 数据表 - 翻译响应元素
- android - 应用程序在后台时接收通知的问题