Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP / Mongo: how do you update nested data?

I've been playing around with Mongo for about a week now and I still can't work out how to modify nested arrays in Mongo with php.

So here is a sample document...

array (
  '_id' => new MongoId("4cb30f560107ae9813000000"),
  'email' => '[email protected]',
  'firstname' => 'Maurice',
  'lastname' => 'Campobasso',
  'password' => 'GOD',
  'productions' => 
  array (
    0 => 
    array (
      'title' => 'a',
      'date' => '1286811330.899',
    ),
    1 => 
    array (
      'title' => 'b',
      'date' => '1286811341.183',
    ),
    2 => 
    array (
      'title' => 'c',
      'date' => '1286811350.267',
    ),
    3 => 
    array (
      'title' => 'd',
      'date' => '1286811356.05',
    ),
  ),
)

What I wan't to do is delete an array inside the productions array, but I can't work out how. I've been playing with 'update('$pull' => ...etc)' but I haven't been able to make it work.

like image 891
cybermotron Avatar asked Jun 22 '26 13:06

cybermotron


2 Answers

OK, there are a few ways to do this. In your case, I would do something like

mymongoobject.update( $unset : { "productions.2" : 1 } }

That's basically saying to unset the ".2" element of productions. Some docs here.

Now $pull should also work, but it's a little tougher because "productions" is actually an array of arrays (or objects with sub-objects). So you'd have to match arrays exactly:

mymongoobject.update( $pull : { "productions" : {'title':'d', 'date':'1286811356.05'} }

In the case above, the unset is probably the easiest option (though it will leave a "hole" in the array)

like image 55
Gates VP Avatar answered Jun 24 '26 01:06

Gates VP


That is actually very easy, unlike traditional sql stuff you just modify the whole data and pass it back.

$cursor = $mongo->yourDB->yourCollection->findOne("_id",4cb30f560107ae9813000000);
//let's remove last item on productions
array_splice($cursor["productions"],2);
//and update the mongo document
echo $mongo->yourDB->yourCollection->update($cursor);
//it echoes 1 if successful

hope it helps.

like image 44
Sinan Avatar answered Jun 24 '26 01:06

Sinan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!