如何使用C#版MongoDb Driver 2.18创建不存在的MongoDb文本索引
解决方案(MongoDB.Driver 2.18版本)
在2.18版本的MongoDB.Driver中,可通过以下方式实现仅在索引不存在时创建索引:
1. 检查索引是否存在
通过_collection.Indexes.ListAsync()获取集合的所有索引,随后根据索引名称或键定义判断目标索引是否已存在。
2. 创建索引
确认索引不存在后,使用CreateOneAsync(推荐异步)或CreateOne(同步)方法创建索引。
完整代码示例
protected readonly IMongoDatabase _database; protected readonly IMongoCollection<Product> _collection; public ProductConfiguration(IMongoDatabase mongoDatabase) { _database = mongoDatabase; _collection = _database.GetCollection<Product>(typeof(Product).Name); } public async Task CreateProductIndexAsync() { // 定义目标索引:以Name字段升序建立唯一索引,指定索引名称 var indexKeys = Builders<Product>.IndexKeys.Ascending(p => p.Name); var indexOptions = new CreateIndexOptions { Unique = true, Name = "Product_Name_Unique" }; var indexModel = new CreateIndexModel<Product>(indexKeys, indexOptions); // 获取集合所有现有索引 var existingIndexesCursor = await _collection.Indexes.ListAsync().ConfigureAwait(false); var existingIndexes = await existingIndexesCursor.ToListAsync().ConfigureAwait(false); // 通过索引名称判断是否存在 bool indexExists = existingIndexes.Any(idx => idx["name"].AsString == indexOptions.Name); if (!indexExists) { // 创建索引 await _collection.Indexes.CreateOneAsync(indexModel).ConfigureAwait(false); // 若需同步操作,替换为:_collection.Indexes.CreateOne(indexModel); } }
补充说明
- 若不想通过索引名称判断,也可解析索引的键定义(
idx["key"]字段)与目标索引的键进行比对,适合未指定索引名称的场景。 - 索引支持更多配置项,比如设置过期时间
ExpireAfter、全文索引等,可按需调整CreateIndexOptions参数。
内容的提问来源于stack exchange,提问作者theGhostN
相关产品推荐
相关产品推荐

