我一直在开发一个使用 MongoDB 作为存储形式的 Java 应用程序,但是我遇到了一个问题。当用户在我的应用程序中添加评论时,它会将文档添加到评论集合中,然后对统计数据进行更新插入。但是, upsert 只添加第一次(更新或插入新数据后没有调用)。以下是相关代码:
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
}
请注意 stat 集合中缺少的“_id”和“_class”。我的 mongo 或 tomcat 日志中没有任何错误。有没有人遇到过这个问题或知道交易是什么?谢谢你的帮助!
注意: 如果我删除 upsert 并正常添加统计信息,一切都会很好(当然,这会为单个实体添加多个统计信息,这是不可取的)