2016-01-19 91 views
0

我使用Java代碼蒙戈DB指標名稱

dbCollection.createIndex("accountNumber"); 

當我看到使用

db.accounts.getIndexes() 

「accountNumber_1」

指數我得到的指數名稱創建蒙戈DB集合索引

如何獲得與文檔字段相同的索引名稱?或如何給索引名稱?

命名索引是重要的還是我可以忽略它?

+0

是否有任何具體原因需要使用索引名稱?當你提示mongo查詢中使用哪個索引時,你需要指定索引的*字段名稱,而不是實際的索引名稱:db.users.find()。hint({age:1})' – Lix

+1

你可以忽略這個。這個名字是沒有意義的 – Sammaye

回答

1

當我們在users

> db.users.createIndex({name: 1}) 
{ 
     "ok" : 0, 
     "errmsg" : "Index with name: name_1 already exists with different option 
s", 
     "code" : 85 
} 

name: name_1返回文檔創建索引,那麼我們可以通過getIndexes()

> db.users.getIndexes() 
[ 
     { 
       "v" : 1, 
       "key" : { 
         "_id" : 1 
       }, 
       "name" : "_id_", 
       "ns" : "test.users" 
     }, 
     { 
       "v" : 1, 
       "unique" : true, 
       "key" : { 
         "name" : 1 
       }, 
       "name" : "name_1", 
       "ns" : "test.users", 
       "background" : true, 
       "safe" : null 
     } 
] 

我們知道的景氣指數,該name_1是指數的只是價值name。並使用密鑰name爲文檔users創建索引。我認爲name_1name的價值,以滿足BSON結構。我們可以忽略它...

0

您可以使用createIndex方法的其他變體創建您想要的名稱的索引,請參閱java API here


public void createIndex(DBObject keys, 
         DBObject options) 
Creates an index on the field specified, if that index does not already exist. 
Prior to MongoDB 3.0 the dropDups option could be used with unique indexes allowing documents with duplicate values to be dropped when building the index. Later versions of MongoDB will silently ignore this setting.

Parameters: keys - a document that contains pairs with the name of the field or fields to index and order of the index options - a document that controls the creation of the index. MongoDB documentation Index Creation Tutorials

可以相應MongoDB的文檔here

基本上第二個參數'options'包含一個顯式提供索引名稱的選項。