6

我一直在开发一个使用 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 并正常添加统计信息,一切都会很好(当然,这会为单个实体添加多个统计信息,这是不可取的)

4

2 回答 2

2

我认为您可以尝试用@Document(collection = "colName")- 我今天遇到同样的问题来注释您的课程。Upserts 的工作有时真的很奇怪:我仍然无法找到始终如一地获取错误的方法。

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

于 2013-02-22T16:37:29.293 回答
0

我遇到了一个问题,我正在更新一个已经有 id 的对象,所以 _id 被保留了。但是,_class 没有保存。我的解决方法是向我的班级添加一个成员,以确保 _class 数据始终存在:

@Field("_class")
protected String _class = Foo.class.getName();
于 2014-11-12T15:36:14.363 回答