[DataBase] MongoDB (7) MongoDB 索引

MongoDB 索引

1. 建立索引

唯一索引
db.passport.ensureIndex( {"loginname": 1}, {"unique": true});
复合唯一索引
db.passport.ensureIndex( {"loginname": 1,“age”: 1}, {"unique": true});
去除重复(不建议使用,建议自己处理重复数据)
db.passport.ensureIndex( {"loginname": 1}, {"unique": true, “dropDups”: true});

2. 稀疏索引
db.passport.ensureIndex( {“email”: 1}, {"unique": true, “sparse”: true});

3. 查看索引
db.passport.getIndexes()

 

> db.passport.getIndexes()
[
	{
		"v" : 1,
		"key" : {
			"_id" : 1
		},
		"ns" : "bike.passport",
		"name" : "_id_"
	},
	{
		"v" : 1,
		"unique" : true,
		"key" : {
			"loginname" : 1
		},
		"name" : "loginname_1",
		"ns" : "bike.passport"
	}
]

 


4. 删除索引

> db.passport.dropIndex(“loginname_1”)

 

一个初始化脚本
shell init db index  
  1 db = connect("localhost/bike");                                                                                                                                                                                                                                                       
  2 function init_index()
  3 {
  4     db.passport.ensureIndex( {"loginname": 1}, {"unique": true});
  5 
  6     db.bike.ensureIndex( {"bike_num": 1}, {"unique": true} );
  7     db.bike.ensureIndex( {"lock_id": 1}, {"unique": true} );
  8     db.bike.ensureIndex( {"lock_num": 1}, {"unique": true} );
  9     db.bike.ensureIndex( {"dealerid": 1} );
 10 
 11     db.order.ensureIndex( {"uid": 1});
 12     db.order.ensureIndex( {"bikeid": 1});
 13 
 14     db.deposit.ensureIndex( {"uid": 1} );
 15     db.deposit.ensureIndex( {"loginname": 1} );
 16 
 17     printjson("index init is ok");
 18 }
 19 
 20 init_index();
 21 

 

 

 


固定集合
TTL索引
全文本索引
地理空间索引

 

你可能感兴趣的:([DataBase] MongoDB (7) MongoDB 索引)