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

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
}
主站蜘蛛池模板: 南皮县| 南华县| 禹城市| 韶山市| 通道| 来安县| 加查县| 达日县| 阳原县| 武平县| 通许县| 青神县| 北碚区| 荥经县| 清丰县| 海宁市| 沾化县| 淅川县| 金山区| 万荣县| 陵水| 伊吾县| 芦溪县| 东山县| 阿瓦提县| 新平| 赣州市| 通城县| 偏关县| 台湾省| 富阳市| 漳浦县| 庆阳市| 柳州市| 永定县| 海城市| 梧州市| 安远县| 长阳| 大竹县| 博野县|