Java MongoTemplate:Upserts不生成ObjectId

use*_*661 6 java mongodb spring-mongo

我一直在研究一个使用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 ) 
},
{ 
    "_id" : ObjectId( "50ab0691e4b0775cf7daacad" ),
    "_class" : "com.test.models.comment.UserComment",
    "userId" : 4,
    "ownerId" : 3,
    "comment" : "Another test",
    "type" : "ART",
    "entity" : "759446489112216656",
    "date" : Date( 1353385617619 ) 
}
Run Code Online (Sandbox Code Playgroud)

......和我单身,孤独的统计......

{ 
    "entity" : "759446489112216656",
    "total" : 1 
}
Run Code Online (Sandbox Code Playgroud)

请注意stat集合中缺少"_id"和"_class".我的mongo或tomcat日志中没有出现任何错误.有没有人遇到过这个问题或知道这笔交易是什么?谢谢你的帮助!

注意: 如果我删除upsert并正常添加stat,那么一切都会正常添加(当然,这会为单个实体添加多个统计信息,这是不可取的)

use*_*ser 2

我认为你可以尝试用@Document(collection = "colName")- 我今天遇到了同样的问题来注释你的课程。更新插入有时真的很奇怪:我仍然无法找到一致地获取错误的方法。

实际上我所做的是创建一个解决方法(临时的,只是“使其工作”),我必须检查对象中是否存在“_id”,如果它为空,我使用保存,如果不是 - 我使用更新。是的,这很奇怪,但它有效。