官术网_书友最值得收藏!

How to do it...

  1. We begin by connecting to the mongo shell of the server and viewing all indexes on the system:
> db.mockdata.getIndexes()

The following result is obtained:

[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "mydb.mockdata"
},
{
"v" : 2,
"key" : {
"city" : 1,
"first_name" : 1
},
"name" : "city_1_first_name_1",
"ns" : "mydb.mockdata"
}
]
  1. Execute a dropIndex() command to delete a particular index:
> db.mockdata.dropIndex('city_1_first_name_1')

You should see the following result:

{ "nIndexesWas" : 2, "ok" : 1 }
  1. Let's recreate the index:
> db.mockdata.createIndex({'city':1}, {name: 'city_index'})

{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
  1. Run getIndexes() to fetch all indexes of the collection:

> db.mockdata.getIndexes()

We should see the following result:

[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "mydb.mockdata"
},
{
"v" : 2,
"key" : {
"city" : 1
},
"name" : "city_index",
"ns" : "mydb.mockdata"
}
]
  1. Try creating the index again on the city field:
> db.mockdata.createIndex({'city':1})

You should see the following message:

{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 2,
"numIndexesAfter" : 2,
"note" : "all indexes already exist",
"ok" : 1
}
  1. Check the size of the index:
stats = db.mockdata.stats()
stats["totalIndexSize"]

It should show the following result:

1818624
  1. Let us view the size of each index:
stats["indexSizes"]

This should show the following result:

{ "_id_" : 905216, "city_index" : 913408 }
  1. Re-index city_index:
> db.mockdata.reIndex('city_index')

The following result is obtained:

{
"nIndexesWas" : 2,
"nIndexes" : 2,
"indexes" : [
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "mydb.mockdata"
},
{
"v" : 2,
"key" : {
"city" : 1
},
"name" : "city_index",
"ns" : "mydb.mockdata"
}
],
"ok" : 1
}
主站蜘蛛池模板: 阿克陶县| 项城市| 福清市| 正镶白旗| 屯门区| 托里县| 东安县| 封丘县| 牙克石市| 温泉县| 重庆市| 台州市| 错那县| 兴仁县| 永城市| 承德市| 信宜市| 门源| 安溪县| 洛浦县| 武陟县| 营山县| 新平| 廊坊市| 宁国市| 贵州省| 洮南市| 林西县| 无为县| 图们市| 怀集县| 佛山市| 株洲市| 越西县| 吉木萨尔县| 进贤县| 武夷山市| 莱阳市| 平度市| 福安市| 顺平县|