我正在尝试在原子操作中增加帖子的评论投票,所以如果在DownVoters和UpVoters评论列表中不存在当前用户名,我试图提升帖子的评论。但是下面的查询真的很奇怪有时可行但不总是如此。我已经检查过DownVoters和UpVoters列表中不存在用户名,但仍然低于查询不起作用。以下查询有什么问题?
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);
答案 0 :(得分:1)
您的代码看起来很好。我写了很多次,它按预期工作。在任何字段名称中都可能是简单的人为错误(就像你上面的Commments - > Comments)。
我建议使用mongodb shell来解决确切问题。
首先插入测试文档:
{
"Comments": [
{
"DownVoters": [],
"Score": 2,
"UpVoters": [],
"_id": 1
},
{
"_id": 2,
"Score": 2,
"UpVoters": [],
"DownVoters": []
}
],
"_id": 1
}
此外,我已将您的c#查询翻译为本机mongodb语法,因此您可以在mongodb shell update中使用它。
您的查询:
{"Comments._id": 1, "Comments.DownVoters" : { "$nin" : ["andrew"]},
"Comments.UpVoters" : { "$nin" : ["andrew"]} }
您的更新:
{"$push" : { "Comments.$.UpVoters": "andrew" },
"$inc" : {"Comments.$.Score": 1} }
尝试一下,回答我们,回答问题所在。