AnyOne
AnyOne

Reputation: 931

MongoDB increment query does not work as expected

I am trying to increase post's comment vote in atomic operation so I am trying to upvote post's comment if current username is not exist in DownVoters and UpVoters list of comment.But below query really strangely sometimes works but not always. I have checked that username is not exist in DownVoters and UpVoters list but still below query does not work. What is wrong at below query ?

var query = Query.And(Query.EQ("Comments._id", commentId), Query.NotIn("Comments.DownVoters", username));
var update = Update.Push("Commments.$.UpVoters",username).Inc("Commments.$.Score", 1);
collection.Update(query, update);

Upvotes: 1

Views: 1596

Answers (1)

Andrew Orsich
Andrew Orsich

Reputation: 53685

Your code looks fine. I've wrote it many times and it work as expected. It can be simple human mistake in any field name (like you have above Commments -> Comments).

I suggest to play in mongodb shell to figure out exact problem.

First of all insert test document:

{
  "Comments": [
    {
      "DownVoters": [],
      "Score": 2,
      "UpVoters": [],
      "_id": 1
    },
    {
      "_id": 2,
      "Score": 2,
      "UpVoters": [],
      "DownVoters": []
    }
  ],
  "_id": 1
}

Also I've translated your c# query to native mongodb syntax, so you can use it in mongodb shell update.

Your query:

{"Comments._id": 1, "Comments.DownVoters" : { "$nin" : ["andrew"]},
                    "Comments.UpVoters" : { "$nin" : ["andrew"]} }

Your update:

{"$push" : { "Comments.$.UpVoters": "andrew" }, 
 "$inc" : {"Comments.$.Score": 1} } 

Try it out and come back to us with answer what was a problem.

Upvotes: 1

Related Questions