简体   繁体   中英

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM