db.student.ensureIndex({name: 1})
给name字段创建索引, 1为指定按升序创建索引,如果你想按降序来创建索引指定为-1即可。
实例
 
db.student.getIndexes()
查看索引
 
db.student.find({"name": "yhy"}).explain()
查看是否使用到了索引(由于MongoDB调优)
 
db.student.dropIndex("name_1")
删除索引
 
db.students.ensureIndex({name: 1}, {unique: true})
给name字段创建一个唯一键索引,那么再给students表增加一条行document,且name与之前存在的document的name值相同,那么就会报错, 如:增加一条document
db.students.insert({name: "yhy"})
报错的信息如下:
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 11000,
"errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: test.students.$name_1 dup key: { : \"yhy\" }"
}
})

相关文章:

  • 2021-12-03
  • 2021-12-19
  • 2021-12-03
  • 2021-11-23
  • 2022-01-18
  • 2021-09-18
  • 2021-12-06
  • 2021-10-05
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-11-19
  • 2021-04-25
  • 2022-02-09
  • 2021-11-30
  • 2021-10-28
相关资源
相似解决方案