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

1

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.