Rohan Kumar
Rohan Kumar

Reputation: 40639

How To use pull in mongodb using php

I want to delete information from a document but the code runs and no error occurs.But it doesn't delete the record. I haave data like that

{       
  "id": "12345",
   "info": [
    {
        "sno":1
        "name": "XYZ",
        "email": "[email protected]"
    },
    {
        "sno":2
        "name": "XYZ",
        "email": "[email protected]"
    }
  ]      
}

and I want to delete data where id=12345 and info.sno=2 my php code id

<?
     $m=new Mongo();
     $db=$m->database;
     $cond=array("id"=>'12345');
     $data=array('$pull'=>array("info.sno"=>2));
     //I used before this $data=array('$pull'=>array("info"=>array("sno"=>2)));
     echo json_encode($data);
     $db->info->update($cond,$data);
     $st=$db->Command(array("getlasterror"=>1));
?>

I run mongo db command like:

    db.info.update({"id":12345},{'$pull':{"info":{"sno":2}}});

Upvotes: 0

Views: 790

Answers (1)

kris
kris

Reputation: 23592

Your commented out line is correct:

test> db.foo.findOne()
{
    "_id" : ObjectId("4f74737cc3a51043d26f4b90"),
    "id" : "12345",
    "info" : [
            {
                    "sno" : 1,
                    "name" : "XYZ",
                    "email" : "[email protected]"
            },
            {
                    "sno" : 2,
                    "name" : "XYZ",
                    "email" : "[email protected]"
            }
    ]
}
test> db.foo.update({"id":"12345"}, {"$pull":{info:{sno:2}}})
test> db.foo.findOne()
{
    "_id" : ObjectId("4f74737cc3a51043d26f4b90"),
    "id" : "12345",
    "info" : [
            {
                    "sno" : 1,
                    "name" : "XYZ",
                    "email" : "[email protected]"
            }
    ]
}

Upvotes: 2

Related Questions