[英]What does Java do when we import packages multiple times in the same class?
[英]what does ensureIndex() commad do in java/scala mongo driver when its called multiple times
我是mongodb索引的新手,我想問一下我是否在mongo shell中這樣做
db.myCollection.ensureIndex({"Email":1})
它成功創建了索引,但是如果再次運行此命令,mongo shell將顯示此消息
{ "numIndexesBefore" : 2, "note" : "all indexes already exist", "ok" : 1 }
當我在scala / java代碼中執行相同操作時,這是理想的情況
class Test {
def myFunction= {
var index=collection.ensureIndex(new BasicDBObject("Email":1))
}
}
當我兩次調用此函數時,它不會引發任何異常,因為mongo shell的index already exist
確實index already exist
所以我想知道此命令的作用
collection.ensureIndex(new BasicDBObject("Email":1))
}
當我們再次調用它時做
object Demo extends App
{
var t=Test()
t.myFunction
t.myFunction//what happends here ? what does this ensureIndex command do
}
請指導我謝謝
根據文檔,如果索引不存在,則ensureIndex
在指定的字段上創建索引,因此后續調用除了檢查該索引已存在以外,不執行任何其他操作。
正如上面的答案所暗示的,多次調用不會執行任何操作。
您沒有得到任何異常,因為當您第二次或第三次調用確保索引時,MongoDB不會引發異常,它只是為您提供一個“索引已存在”的JSON。
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 1,
"note" : "all indexes already exist",
"ok" : 1
}
與第一次或添加其他索引時返回JSON的方式相同。
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.