使用 createIndex
方法
你可以在 MongoDB shell 或者通过编程语言的 MongoDB 驱动来创建索引。以下是使用 MongoDB shell 的示例:
// 创建一个单字段索引
db.collection.createIndex({ fieldName: 1 })
// 创建一个复合索引
db.collection.createIndex({ field1: 1, field2: -1 })
// 创建一个唯一索引
db.collection.createIndex({ fieldName: 1 }, { unique: true })