2

I am using mongodb library for codeigniter.i want to delete element from embedded document. my collection is as follows-

{
"_id" : ObjectId("56503a272f170d30298b45ad"),
"gm_creation_time" : "2015-11-21 09:32:23",
"gm_favourites" : [
    {
        "gm_user_id" : "55f90ccf2f170d79048b4570",
        "gm_id" : "56503a272f170d30298b45ad",
        "date" : "2015-11-21 09:32:40"
    }
],
"gm_members" : [
    "560391de2f170d1e108b4574",
    "55f90ccf2f170d79048b4570"
],
"gm_name" : "Sunny@ccs",
"gm_owner" : "55f90ccf2f170d79048b4570",
"gm_photo" : null,
"gm_posts" : [ ],
"gm_type" : "1",
"gm_updation_time" : "2015-11-21 09:32:40"
}

How can I delete from favorites according to gm_user_id. I am new to codeigniter+mongodb. please help

Masoud
  • 8,020
  • 12
  • 62
  • 123
sneha
  • 41
  • 5
  • Possible duplicate of [How do I remove a field completely from Mongo?](http://stackoverflow.com/questions/6851933/how-do-i-remove-a-field-completely-from-mongo) – Luboš Turek Nov 21 '15 at 10:32

2 Answers2

3

Use the $pull array modifier operator to remove all instances of a value or values that match a specified condition from an existing array.

The following mongo operation updates all documents in the collection to remove the object with "gm_user_id" property that has a value of "55f90ccf2f170d79048b4570" from the array gm_favourites:

db.collection.update(
    { },
    { 
        "$pull": { 
            "gm_favourites": { 
                "gm_user_id": "55f90ccf2f170d79048b4570" 
            }
        } 
    },
    { "multi": true }
);

This will translate to PHP as follows:

$connection = new Mongo();
$db = $connection->selectDB('dbname');
$collection = $db->selectCollection('collection_name');

$filter = array();
$remove_document = array(
    '$pull' => array(
        'gm_favourites' =>  array(
            'gm_user_id' =>  '55f90ccf2f170d79048b4570',
        ) 
    ) 
);
$options['multiple'] = true;

$collection->update($filter, $remove_document, $options);
chridam
  • 100,957
  • 23
  • 236
  • 235
1

If you want to remove the embedded document based on gm_user_id use the following command. (Assuming the collection name is favorites):

db.test.update( {} , {$pull:{'gm_favourites':{'gm_user_id' : '55f90ccf2f170d79048b4570'}}})

The above command will remove the matching embedded document.

Sarath Nair
  • 2,828
  • 2
  • 21
  • 36
  • how can I use this in codeigniter, i have tried like this- $this->mongo_db->pull('gm_favourites',array('gm_id' => $groupId, 'gm_user_id' => $userId))->update('group_master'); but it is not working – sneha Nov 21 '15 at 11:26