Mongodb ensure the correctness of array and count in single query
{ id = "castle",
tags = [ "Red", "Black", "White" ], count:3 }
I have a collection like above, a tags array with a unique item and counter of array.
I would like to add a tags and increment the tags count in a single query.开发者_开发技巧
var query = Query.EQ("id", "castle");
var update = Update.AddToSetWrapped("tags", "White").Inc(count", 1); Photo.Update(query, update);
What I expected is that the first part of this query is invalid because "White" is already in tags array so $inc will not execute.
But the actual result is tag doesn't insert(correct) and the counter get increment(surprise!).
I would like to know if I can do it in single query in above case.
I am using mongodb offical C# driver.
This is actually a limitation of MongoDB. There is no "trigger" or "update x if addToSet
works".
There is an outstanding bug in the MongoDB JIRA system here. There's a similar bug here. If you want this fixed you'll have to Vote on them. Of course, that first one has been open for over a year and is not scheduled, so it's not currently deemed that important.
Given MongoDB limitations, you can query records with id="castle" that don't have a "White" tag. Then run the update only if you get any records.
精彩评论