可以使用 ensueIndex ,或者 createIndex ,不过,mongoDB 3.0开始,ensueIndex 已经已经被废弃,所以,建议使用createIndex创建INDEX。
--1.数据情况
db.employees.find();
{ "_id" : ObjectId("64a8e771c531db7498ca2081"), "empid" : 100, "name" : "mahan", "age" : 30 }
{ "_id" : ObjectId("64a8e795c531db7498ca2082"), "empid" : 101, "name" : "liuzy", "age" : 25 }
{ "_id" : ObjectId("64a8e7e3c531db7498ca2083"), "empid" : 102, "name" : "wangjia", "age" : 30, "hire_date" : "2012-10-10" }
{ "_id" : ObjectId("64a8e841c531db7498ca2084"), "empid" : 103, "name" : "zengyin", "age" : 32, "hire_date" : "2018-09-10", "job" : "sales" }
比如,我们想在 employees.empid上创建索引:
--2.创建索引
db.employees.createIndex({empid:1});
db.employees.createIndex({empid:1});
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
--3.查找EMPLOYEES集合的索引索引
> db.employees.getIndexes();
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "ordb.employees"
},
{
"v" : 2,
"key" : {
"empid" : 1
},
"name" : "empid_1",
"ns" : "ordb.employees"
}
]
--4.删除索引
> db.employees.dropIndex({empid:1});
{ "nIndexesWas" : 2, "ok" : 1 }
--5.再次确认索引被删除
> db.employees.getIndexes();
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "ordb.employees"
}
]
|