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

如何使用MongoDB .NET驱动创建聚集索引?2.19.0版本是否支持?

MongoDB .NET驱动2.19.0创建聚集索引方法

MongoDB.Driver 2.19.0版本完全支持创建聚集索引,你之前的尝试可能是参数配置有误。以下是两种正确的实现方式及关键注意事项:

1. 创建集合时指定聚集索引

使用Database.CreateCollectionAsync时,通过CreateCollectionOptions配置聚集索引:

// 替换为你的文档实体类型
public class YourDocument
{
    public ObjectId Id { get; set; }
    // 其他业务字段...
}

var createOptions = new CreateCollectionOptions
{
    ClusteredIndex = new ClusteredIndexOptions
    {
        // 聚集索引的键,通常使用_id字段
        Key = new IndexKeysDefinitionBuilder<YourDocument>().Ascending(doc => doc.Id),
        Name = "clustered_index",
        Unique = true // 根据业务需求设置是否唯一
    }
};

await database.CreateCollectionAsync("your_collection_name", createOptions);

2. 在空集合上创建聚集索引

如果集合已创建但无数据,可以使用Collection.Indexes.CreateOneAsync创建聚集索引:

var indexModel = new CreateIndexModel<YourDocument>(
    Builders<YourDocument>.IndexKeys.Ascending(doc => doc.Id),
    new CreateIndexOptions 
    { 
        IsClustered = true, 
        Name = "clustered_index" 
    }
);

await collection.Indexes.CreateOneAsync(indexModel);

关键注意事项

  • 聚集索引是MongoDB 5.0及以上版本的功能,请确保你的MongoDB服务器版本符合要求,驱动2.19.0已适配该特性。
  • 每个集合只能有一个聚集索引,且必须基于单个字段(复合键不支持聚集索引)。
  • 如果集合中已有文档,无法创建聚集索引,需先清空集合或重新创建集合后再操作。

内容的提问来源于stack exchange,提问作者Oscar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 06:37:04