You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 11:25:14