在 MongoDB 中,建立索引主要通过 createIndex() 方法(旧版本为 ensureIndex(),已弃用)。下面按常见场景给你说明。
db.collection.createIndex(keys, options)
keys:指定要索引的字段及排序方式
1 表示升序-1 表示降序options:索引选项(可选)db.users.createIndex({ username: 1 })
db.users.createIndex({ age: 1, name: -1 })
常用于多条件查询,注意字段顺序
db.users.createIndex({ email: 1 }, { unique: true })
db.users.createIndex({ _id: "hashed" })
db.articles.createIndex({ content: "text" })
db.logs.createIndex(
{ createdAt: 1 },
{ expireAfterSeconds: 3600 }
)
db.orders.createIndex(
{ status: 1 },
{ partialFilterExpression: { status: "active" } }
)
db.collection.getIndexes()
db.collection.dropIndex("index_name")
db.collection.dropIndexes()
db.users.createIndex(
{ username: 1 },
{ background: true }
)
MongoDB 4.2+ 默认后台构建,无需显式指定
explain() 分析索引是否生效如果你有 具体集合结构或查询语句,我可以帮你设计更合适的索引方案。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。