Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unset all records string in mongodb using php?

Tags:

php

mongodb

My DB records somthing like this...

{
   "_id": ObjectId("50118b145e69ef2c0e007a2"),
   "class": "customer",
   "dbid": "1829",
   "value": "[email protected]" 
}

{
   "_id": ObjectId("50118b145e69ef2c0e007a1"),
   "class": "customer",
   "dbid": "1828",
   "value": "[email protected]" 
}

My PHP code

define('DB_HOST', 'localhost');
define('DB_DBNAME', 'mydb');
define('DB_USERNAME', 'mongouser');
define('DB_PASSWORD', 'mongopasswd');
define('DB_DSN', "mongodb://". DB_USERNAME .":". DB_PASSWORD ."@". DB_HOST ."/". DB_DBNAME);
$DB = new Mongo(DB_DSN);
if (!$DB) { die('DB Connection failed!'); }

$MONGODB = $DB->DB_DBNAME;
$COLLECTION = $MONGODB->my_customer;

I try to use $unset "dbid" from all records like delete field by using the code below but it doesn't works.

PS: I try to search in stackoverflow but always show tutorial in commmand line but I need it works in PHP script.

$COLLECTION->update(array('$unset' => array('dbid' => true)));

I try this code didn't work too. :(

$COLLECTION->update(array('$unset' => array('dbid' => true)), array('multiple'=>true));

If you guys have any ideas please share..

Thank you so much. :)


--------- Updated ----------

I have already found the solution of the problem.

@Marc You're right! I forgot the criteria and I found my code is wrong too.

The problem is mongodb extension is confused with the define value. (It think DB_DBNAME is a database name) so, I added+changed some code look like this.

$mongodb_name = DB_DBNAME;
$MONGODB = $DB->$mongodb_name;
$COLLECTION = $MONGODB->my_customer;

Now, I try @Marc example code

To remove ($unset) string from all records... (Works!)

$COLLECTION->update(array('dbid' => array('$exists' => true)), array('$unset' => array('dbid' => true)), array('multiple' => true));

To insert string into all records... I use this code. (Works!)

$COLLECTION->update(array('dbid' => array('$exists' => false)), array('$set' => array('dbid' => 'new_value')), array('multiple' => true));
like image 357
thegodth Avatar asked Feb 18 '26 05:02

thegodth


1 Answers

You forgot the critearia, so the solution would be:

$COLLECTION->update(
    array('dbid' => array('$exists' => true)),
    array('$unset' => array('dbid' => true)),
    array('multiple' => true)
)
like image 163
Marc Avatar answered Feb 20 '26 19:02

Marc