小编use*_*661的帖子

Java MongoTemplate:Upserts不生成ObjectId

我一直在研究一个使用MongoDB作为存储形式的Java应用程序,但是我遇到了一个问题.当用户在我的应用程序中添加注释时,它会将文档添加到注释集合中,然后对统计数据执行upsert.但是,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);
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是我的评论集合中的结果示例:

{ 
    "_id" : ObjectId( "50ab0566e4b0ea8f74b82d48" ),
    "_class" : "com.test.models.comment.UserComment",
    "userId" : 4,
    "ownerId" : 3,
    "comment" : "Test comment",
    "type" : "ART",
    "entity" : "759446489112216656",
    "date" : Date( 1353385318079 …
Run Code Online (Sandbox Code Playgroud)

java mongodb spring-mongo

6
推荐指数
1
解决办法
1559
查看次数

标签 统计

java ×1

mongodb ×1

spring-mongo ×1