PHP MongoDB $exist not working
Asked Answered
M

3

5
$collection->update(array("_id"=>new MongoId($uid), "phonenumber"=> $exist => array(FALSE),$set("phone"=>"1223444"));

I would like to know why my $exist query is not working with PHP, and Mongodb if anyone could point me in the right direction that would be helpful.

Ok in the collection database there is no row called phonenumber and if there is no phonenumber i want it to insert one, but if there is phonenumber dont do anything.

Medication answered 15/7, 2012 at 3:58 Comment(2)
Clearly you have a syntax error in the code above. However, it's not clear what logic you are trying to capture here. Can you be more specific about what you are trying to query/update?Hyohyoid
@Medication why you marked the wrong answer to be right?! oliviercuyp was rightEchelon
H
11

You have a couple of syntax issues.

  1. You're missing arrays at the second level
  2. Your operators need single quotes around them ($exist)

Here is a cleaned up sample:

$collection->update(
    array( "_id"=> new MongoId($uid), 
           array("phonenumber"=> array('$exists' => false))
         ),
    array( '$set' => array("phone"=>"1223444") )
);
Hyohyoid answered 15/7, 2012 at 4:22 Comment(2)
what I can say is in mongodb collection there is not a row atm with phonenumber and I want to add it when they input it.Medication
@Medication if you are updating a specific document (as identified by _id) and there isn't a phonenumber field yet .. just go ahead and $set it. The '$exist' check is unnecessary unless you're trying to avoid overriding a value that is already set.Gurnard
T
3

This should be :

$collection->update(
    array( 
        "_id"         => new MongoId($uid), 
        "phonenumber" => array('$exists' => false)
    ),
    array( '$set' => array("phone"=>"1223444") )
);

There was an array level too much in the response Gates VP

Tailrace answered 20/12, 2013 at 16:54 Comment(0)
R
0

Try to do this not equal operator

$collection->update(
    array( "_id"=> new MongoId($uid)),
    array( '$set' => array("phone"=>"1223444") )
);
Retardant answered 15/7, 2012 at 4:46 Comment(4)
Nope sadly that is not working either. its not inserting anything into the dbMedication
@RussellHarrower: If there is no row with phonenumber in mongo array, then why you check with field exists?Retardant
but I dont want it updated everytime I run that section of code.Medication
I don't understand your context here clearly. I will try to say what you need, first to add phone field when missing(absent) phone field from document after that don't update with it, is it?Retardant

© 2022 - 2024 — McMap. All rights reserved.