I’m working on a rating system. When a user rates, $inc increments the field, and addToSet adds the user_id to make sure the user only clicks rate once. I am checking if the user_id is already in the x field before updating, but that is another query which I’d rather avoid. Can I reach this purpose without having to write another query? I mean, $addToSet only adds if there is no value like that; can I instead get affected rows? Can you suggest other queries?
Thank you!
..->update(
array("_id" => $idob),
array(
'$inc' => array($type => (int) 1),
'$addToSet' => array("x" => (int) $user_id)
)
);
Ok I see the problem.
The problem is that you need a conditional
$incthere so that it only$incs if it does add to set.This is not possible with a unique index since unique indexes work from the root of the document atm. Also you probably want to use the
$incas a form of pre-aggregation or what not.One method could be:
This will only do the update if that user_id does not already exist in
x.