Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP MongoDB $exist not working

Tags:

php

mongodb

exslt

$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.

like image 953
RussellHarrower Avatar asked Jul 15 '12 03:07

RussellHarrower


People also ask

How do you check if record already exists in MongoDB?

In MongoDB, we can check the existence of the field in the specified collection using the $exists operator. When the value of $exists operator is set to true, then this operator matches the document that contains the specified field(including the documents where the value of that field is null).

How do I search for a specific field in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});

How do I add a new field in MongoDB?

To add field or fields to embedded documents (including documents in arrays) use the dot notation. See example. To add an element to an existing array field with $addFields , use with $concatArrays . See example.

Is null in MongoDB?

The { item : null } query matches documents that either contain the item field whose value is null or that do not contain the item field. The query returns both documents in the collection.


2 Answers

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") )
);
like image 79
Gates VP Avatar answered Oct 05 '22 08:10

Gates VP


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

like image 29
oliviercuyp Avatar answered Oct 05 '22 08:10

oliviercuyp