I've been working on a java app that uses MongoDB as form of storage, however I've run into a problem. When a user adds a comment in my app, it adds the document to the comments collection, then does an upsert for statistical data. However, the upsert only adds the first time (no calls after update or insert new data). Here's the relevant code:
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);
}
}
Here's an example of the results in my comments collection:
{
"_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 )
}
...and my single, lonely stat...
{
"entity" : "759446489112216656",
"total" : 1
}
Notice the missing "_id" and "_class" on the stat collection. I'm not getting any errors in my mongo or tomcat logs. Has anyone ever run into this problem before or know what the deal is? Thanks for your help!
Note: If I remove the upsert and add the stat normally, everything adds fine (this, of course, adds multiple stats for a single entity, which isn't desirable)
I think you could try to annotate your class with the @Document(collection = "colName")
- I had the same issue today. Upserts work really weird sometimes: I still cannot figure the way to get the bug consistently.
Actually what I did is created a workaround (temporary, just "make it work"), where I had to check for "_id" presence in the object and if it is null, I use save, if not - I use update. Yeah, it is weird, but it worked.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With