2016-03-20 21 views
1

Uygulamam çoğunlukla mongodb java sürücüsü 3.2.2 kullanarak mongodb işlem ekler.Eklenti üzerine duplicatekeyexception eğer güncelleme/devam et mongodb java sürücüsü

Eklemek zorunda kalacağım bir belgeyi, yaklaşık% 90'ı ve koleksiyonumda tanımlı iki benzersiz anahtar dizinim var. Özellikle yinelenen bir öğe aldığımda, sürücüye güveniyorum. Belgeyi güncellemek istediğimi bildiğim DuplicateKeyException adlı bir istisna atıyorum.

Belgem aşağıda gibi görünecektir:

{_id:{Object....}, 
name:"something", //unique key 
rollNo:1232, //unique key combined with name 
otherfields 
} 

Benim Java kodu aşağıda benziyor.

try{ 
dbCollections.insert(dbObject); 
}catch(DuplicateKeyException e){ 
// since it is duplicate , lets just update it, 
} 

doğru yolda şu soruları

  1. Am I var? Bu yaklaşıma katılarak herhangi bir tur turu indirmeye çalışıyorum.
  2. Yinelenen öğe durumunda alınan veriler orijinal olandan çok farklı olabilir ve hangi alanların değişebileceğinden emin değilim. Bu yüzden hangi operasyonun burada biraz kafa karıştırıcı güncellemeyi/güncellemeyi seçeceğinden emin değilim.

cevap

1

Eğer durum işleme azaltmak ve kimliği değil var olduğu yeni bir belge yerleştirin da ağ trafiğini kurtaracak UPSERT bayrağı ref bununla güncelleme içine insert açabilirsiniz.

UpdateResult updateOne(Bson filter, 
         Bson update, 
         UpdateOptions updateOptions) 
Update a single document in the collection according to the specified arguments. 
Parameters: 
filter - a document describing the query filter, which may not be null. 
update - a document describing the update, which may not be null. The update to apply must include only update operators. 
updateOptions - the options to apply to the update operation 
Returns: 
the result of the update one operation 
Throws: 
MongoWriteException - if the write failed due some other failure specific to the update command 
MongoWriteConcernException - if the write failed due being unable to fulfil the write concern 
MongoException - if the write failed due some other failure 
İlgili konular