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

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
}
主站蜘蛛池模板: 蒙山县| 习水县| 遵义市| 家居| 固安县| 东丽区| 松桃| 通道| 板桥市| 防城港市| 西林县| 宁海县| 和田市| 玛曲县| 隆安县| 静安区| 武定县| 永安市| 宝丰县| 会理县| 白山市| 班戈县| 沁水县| 蒙阴县| 亳州市| 盐津县| 高邑县| 泉州市| 黄梅县| 永仁县| 叙永县| 南江县| 金昌市| 周至县| 江川县| 永福县| 济宁市| 西华县| 巢湖市| 蒲城县| 云梦县|