2012-11-20 35 views
6

我一直在研究一個使用MongoDB作爲存儲形式的java應用程序,但是我遇到了一個問題。當用戶在我的應用程序中添加評論時,它將文檔添加到評論集合中,然後爲統計數據做一個upsert。但是,upsert只會首次添加(更新後沒有調用或插入新數據)。下面是相關的代碼:Java MongoTemplate:Upserts Not Generating ObjectId

public class CommentDAO implements ICommentDAO { 

    @Autowired 
    @Qualifier(value = "mongoDB") 
    MongoTemplate mongoTemplate; 

    public UserComment addComment(UserComment userComment) { 
     updateStats(userComment, 1L); 
     mongoTemplate.save(userComment); 
     return userComment; 
    } 

    public void updateStats(UserComment userComment, Long offset) { 
     Update update = new Update(); 
     update.inc("total", offset); 
     Query query = query(where("entity").is(userComment.getEntity())); 

     WriteResult wr = mongoTemplate.upsert(query, update, CommentStat.class); 
    } 
} 

下面是我的意見收集結果的一個例子:

{ 
    "_id" : ObjectId("50ab0566e4b0ea8f74b82d48"), 
    "_class" : "com.test.models.comment.UserComment", 
    "userId" : 4, 
    "ownerId" : 3, 
    "comment" : "Test comment", 
    "type" : "ART", 
    "entity" : "759446489112216656", 
    "date" : Date(1353385318079) 
}, 
{ 
    "_id" : ObjectId("50ab0691e4b0775cf7daacad"), 
    "_class" : "com.test.models.comment.UserComment", 
    "userId" : 4, 
    "ownerId" : 3, 
    "comment" : "Another test", 
    "type" : "ART", 
    "entity" : "759446489112216656", 
    "date" : Date(1353385617619) 
} 

...和我的單,孤獨的統計...

{ 
    "entity" : "759446489112216656", 
    "total" : 1 
} 

公告統計數據集中缺少「_id」和「_class」。我沒有在我的mongo或tomcat日誌中發現任何錯誤。有沒有人曾經遇到過這個問題,或知道交易是什麼?謝謝你的幫助!

注: 如果我刪除UPSERT並添加正常的統計,一切都增加了罰款(這一點,當然,增加了多個統計信息的單一實體,這是不可取的)

+0

你能提供你反對,並在統計信息收集更多信息運行的MongoDB的版本?您可以通過運行db.statistics.stats()來打印出mongo shell上的集合摘要 - 用您的集合名稱替換「statistics」。 –

+0

你是如何從統計收集中輸出你的條目的?它不可能在沒有ObjectId()的情況下被插入到MongoDB中 - 所以這是它在upsert之前從Java POV看起來的樣子嗎? –

回答

2

我想你可以嘗試使用@Document(collection = "colName")註釋您的班級 - 我今天有同樣的問題。 Upserts有時非常奇怪:我仍然無法找到一致地獲取bug的方式。

其實我所做的是創建一個解決方法(臨時的,只是「讓它工作」),我必須檢查對象中的「_id」存在,如果它爲空,我使用保存,如果不是 - 我使用更新。是的,這很奇怪,但它工作。

0

我有一個問題,我插入一個已經有一個ID的對象,所以_id被保留。但是_class沒有保存。我的解決方法是將成員添加到我的班,以確保_class數據總是存在:

@Field("_class") 
protected String _class = Foo.class.getName();