mongoDB index

0. stats

show db stats

db.grades.stats()

1. create index

db.students.ensureIndex({class:1,student_name:1})

 unique index

db.students.ensureIndex({class:1,student_name:1},{unique:true})

http://docs.mongodb.org/manual/tutorial/create-an-index/

2. show all indexes in current DB

db.system.indexes.find()

 3. show index for a collection

db.grades.getIndexes()

 4. delete index

db.grades.dropIndex({"student_id":1})

 5. sparse index

only create index on documents which has this key, document that does not has key "title" will be omitted.

db.people.ensureIndex( { title : 1 } , { sparse : 1 } )

6. hint: specify the index to use

use no index

db.people.find().hint({$natural:1})
db.people.find().hint({'title':1}) // btree index

7. geospatial index/ 2d index

db.loc.insert({"loc":[10,10]})
db.loc.ensureIndex({"loc":'2d',type:1})

$near: find nearest neighbor

db.loc.find({"loc":{$near:[10,10]}})

 8. text search

insert

db.text.insert({"words":"apple banana peach"})
db.text.insert({"words":"apple pig"})

create text index

db.text.ensureIndex({"words":"text"})

text search

db.text.find({$text:{$search:"apple"}})

show score for search 

db.text.find({$text:{$search:"apple"}},{score:{$meta:"textScore"}}).sort({scor
{$meta:"textScore"}})

 9. Profiling

http://docs.mongodb.org/manual/tutorial/manage-the-database-profiler/

db.getProfilingLevel()
db.getProfilingStatus()

{ "was" : 0, "slowms" : 100 }

 set profiling

db.setProfilingLevel(2)

show profiling

db.system.profile.find().pretty()
原文地址:https://www.cnblogs.com/phoenix13suns/p/4003135.html