我一直在研究一個使用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並添加正常的統計,一切都增加了罰款(這一點,當然,增加了多個統計信息的單一實體,這是不可取的)
你能提供你反對,並在統計信息收集更多信息運行的MongoDB的版本?您可以通過運行db.statistics.stats()來打印出mongo shell上的集合摘要 - 用您的集合名稱替換「statistics」。 –
你是如何從統計收集中輸出你的條目的?它不可能在沒有ObjectId()的情況下被插入到MongoDB中 - 所以這是它在upsert之前從Java POV看起來的樣子嗎? –