I’ve created a query in PHP which is used to add a user to an array. Right now it checks to see if they exist and if they don’t it adds them to the array. Here’s the full code:
try{ $this->users_db->update(
array(
'_id' => new MongoId($user_id) ,
new MongoId( $group_id ) => array('$nin'=>USER_GROUPS)
),
array(
'$push' => array(USER_GROUPS => array( GROUP_ID => new MongoId($group_id), USER_GROUP_NOTIFY => true ) )
)
); }
catch(Exception $e)
{ return false; }
The problem is that PHP is giving me the Warning “Illegal offset type” since MongoId() is an object and objects can’t be used as keys in arrays. Any ideas about how to work around this?
I think you have the order of your “arguments” to
$ninbackwards. Your query is equivalent to something like this in the mongo shell:Which reads like English, left to right, when pronouncing “
$nin” as “is not in”. A more correct, by MongoDB’s grammar, pronunciation is “does not contain”, so your query is actually saying something like “where some ObjectId does not contain this array”, which makes little sense when said out loud.With that in mind, your query should look like:
When running into issues like this with updates or removes, it’s often useful to try the query spec portion as an argument to
find()orfindOne()to determine what’s wrong there. Once you can find the document you want to update, you can re-write as a call toupdate(),remove(), etc.Also, you should be aware that there is an
$addToSetatomic operator which performs this sort of check for you atomically in the database. You could try:EDIT: For future reference to OP and other askers, see mongodb docs on query operators and mongodb docs on update operators.