Umair Ayub
Umair Ayub

Reputation: 21201

Removing an array element from MongoDB collection does not work

I have this data

{
   "_id": ObjectId("575e66a4c2b503944800002b"),
   "phone": "201-780-8497",
   "orders": [
     "1961682636",
     "43243242" 
  ] 
}

I want to remove order '43243242' where phone is "201-780-8497"

Here is my PHP code

$collection->update(
        array('phone'=>$doc['phone']),
        array('$pull' => array('orders' => array('1961682636'), array('safe' => TRUE))
));

This does nothing, no error, no exception.

Where I am getting wrong?

Upvotes: 2

Views: 38

Answers (1)

chridam
chridam

Reputation: 103305

You update operation should be :

db.collection.update(
    { "phone" : "201-780-8497" },
    { "$pull": { "orders": "43243242" } }
)

and your PHP code:

$collection->update(
    array('phone' => '201-780-8497'),
    array('$pull' => array('orders' => '43243242'))
);

You are getting it wrong on the $pull syntax; you don't need to push the element you want to remove to an array as the $pull document, just reference the value. For a more detailed explanation, consult the docs.

Upvotes: 2

Related Questions