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

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
}
主站蜘蛛池模板: 鸡泽县| 湘潭市| 本溪市| 金秀| 彰武县| 通辽市| 长海县| 房产| 台中市| 凤城市| 房山区| 大城县| 星座| 永登县| 共和县| 岳池县| 共和县| 商城县| 兖州市| 胶南市| 丰台区| 千阳县| 林周县| 中牟县| 高清| 登封市| 庄浪县| 宜章县| 达日县| 辽源市| 乐至县| 屏山县| 兴海县| 阿拉善盟| 勐海县| 阿尔山市| 靖安县| 黄石市| 剑河县| 策勒县| 白银市|