MongoDB聚集索引基本操作
查看当前聚集的全部索引
> db.Account.getIndexes()
[
{
"name" : "_id_",
"ns" : "ChatRoom.Account",
"key" : {
"_id" : 1
},
"v" : 0
}
]
[
{
"name" : "_id_",
"ns" : "ChatRoom.Account",
"key" : {
"_id" : 1
},
"v" : 0
}
]
创建单列索引
> db.Account.ensureIndex({"UserName":1})
--1:ASC -1:DESC
创建单列唯一索引
> db.Account.ensureIndex({"UserName" : 1},{"unique" : true})
创建单列唯一不重复索引
> db.Account.ensureIndex({"UserName" : 1},{"unique" : true,"dropDups" : true})
创建组合索引
> db.Account.ensureIndex({"UserName":1,"Email":1})
> db.Account.getIndexes()
[
{
"name" : "_id_",
"ns" : "ChatRoom.Account",
"key" : {
"_id" : 1
},
"v" : 0
},
{
"_id" : ObjectId("4df7092607444568af61cffd"),
"ns" : "ChatRoom.Account",
"key" : {
"UserName" : 1
},
"name" : "UserName_1",
"v" : 0
},
{
"_id" : ObjectId("4df70dae07444568af61cffe"),
"ns" : "ChatRoom.Account",
"key" : {
"UserName" : 1,
"Email" : 1
},
"name" : "UserName_1_Email_1",
"v" : 0
}
]
> db.Account.getIndexes()
[
{
"name" : "_id_",
"ns" : "ChatRoom.Account",
"key" : {
"_id" : 1
},
"v" : 0
},
{
"_id" : ObjectId("4df7092607444568af61cffd"),
"ns" : "ChatRoom.Account",
"key" : {
"UserName" : 1
},
"name" : "UserName_1",
"v" : 0
},
{
"_id" : ObjectId("4df70dae07444568af61cffe"),
"ns" : "ChatRoom.Account",
"key" : {
"UserName" : 1,
"Email" : 1
},
"name" : "UserName_1_Email_1",
"v" : 0
}
]
删除索引
> db.Account.dropIndex({"UserName":1})
{ "nIndexesWas" : 3, "ok" : 1 }
{ "nIndexesWas" : 3, "ok" : 1 }
> db.Account.dropIndex("UserName_1")
{ "nIndexesWas" : 3, "ok" : 1 }
{ "nIndexesWas" : 3, "ok" : 1 }
删除聚集全部的索引
> db.Account.dropIndexes()
{
"nIndexesWas" : 3,
"msg" : "non-_id indexes dropped for collection",
"ok" : 1
}
> db.Account.getIndexes()
[
{
"name" : "_id_",
"ns" : "ChatRoom.Account",
"key" : {
"_id" : 1
},
"v" : 0
}
]
{
"nIndexesWas" : 3,
"msg" : "non-_id indexes dropped for collection",
"ok" : 1
}
> db.Account.getIndexes()
[
{
"name" : "_id_",
"ns" : "ChatRoom.Account",
"key" : {
"_id" : 1
},
"v" : 0
}
]
--删除全部索引不会删除默认索引
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从零实现富文本编辑器#3-基于Delta的线性数据结构模型
· 记一次 .NET某旅行社酒店管理系统 卡死分析
· 长文讲解 MCP 和案例实战
· Hangfire Redis 实现秒级定时任务,使用 CQRS 实现动态执行代码
· Android编译时动态插入代码原理与实践
· 使用TypeScript开发微信小程序(云开发)-入门篇
· 没几个人需要了解的JDK知识,我却花了3天时间研究
· C#高性能开发之类型系统:从 C# 7.0 到 C# 14 的类型系统演进全景
· 在SqlSugar的开发框架中增加对低代码EAV模型(实体-属性-值)的WebAPI实现支持
· .NET Core中的配置Configuration实战