Search code examples
phpmongodbmultidimensional-arraycollections

Check if in sub array and remove sub-array array


I have read the MongoDB documents however nowhere can I find an example that outlines what I am trying to do.

The closes I come is:

    > t.insert({x: [1,2,3,4,3,2,3,4]})
    > t.find()
    { "_id" : ObjectId("4bde2ad3755d00000000710e"), "x" : [ 1, 2, 3, 4, 3, 2, 3, 4 ] }
    > t.update({x:3}, {$unset:{"x.$":1}})
    > t.find()
    { "_id" : ObjectId("4bde2ad3755d00000000710e"), "x" : [ 1, 2, null, 4, 3, 2, 3, 4 ] }

However, this won't work with what I want to do, as my collection looks like

array (
  'offers' => 
  array (
    0 => 
    array (
      'validto' => 'Thurs',
      'validfrom' => 'Mon',
      'percentage' => '0.05',
      'cashback' => '2',
      'minspend' => '40',
      'status' => 'pending',
      '_id' => '1347940686722',
    ),
    1 => 
    array (
      'validto' => 'Thurs',
      'validfrom' => 'Mon',
      'percentage' => '0.06',
      'cashback' => '3',
      'minspend' => '50',
      'status' => 'pending',
      '_id' => '1347940705277',
    ),
    2 => 
    array (
      'validto' => 'Sun',
      'validfrom' => 'Fri',
      'percentage' => '0.04',
      'cashback' => '2',
      'minspend' => '50',
      'status' => 'pending',
      '_id' => '1347940730663',
    ),
    3 => 
    array (
      'validto' => 'Sun',
      'validfrom' => 'Fri',
      'percentage' => '0.05',
      'cashback' => '3',
      'minspend' => '60',
      'status' => 'pending',
      '_id' => '1347940743513',
    ),
    4 => 
    array (
      'validto' => 'Sun',
      'validfrom' => 'Fri',
      'percentage' => '0.05',
      'cashback' => '5',
      'minspend' => '100',
      'status' => 'pending',
      '_id' => '1347940755230',
    ),
  ),
  'store_id' => new MongoId("5046cd963cd202c49d3140e7"),
)

Now if I want to remove the 3 array (but key here is I won't KNOW if it's 0-4 array; all I have is the data inside that sub array and the _id of the collection row).

Here is what I was thinking. However I got stuck.

$collection->update(array("store_id"=>$this->data['_id'], array("offers._id"=>1347940686722)), array('$unset'=>array("offers.$"=>1)));

Solution

  • Here is how I solved it

    $collection->update(array("store_id"=>new MongoId("5046cd963cd202c49d3140e7")), array('$pull'=>array("offers" =>array("id"=>"1347940755230"),false,false)));