0

My question is if one can use '$slice' with the update() and $push in mongodb.

I already tried this: (with and without casting to (object)

$db->collection->update(
     array('_id' => new MongoId($id)), 

     (object)array( '$push' => 
          array('thumbs' => array(
               '$each' => $items, 
               '$slice' => -5
))));

But the only thing that happens is mongo adding the whole second array in update() to the collection. So I get

thumbs: [ { "$each" : ...

Thanks in advance!

3
  • Why are you casting the update param as an Object?
    – Sammaye
    Apr 26, 2013 at 7:10
  • Because php can't distinguish between objects and arrays in the collection. [] = object and {} = array. But even if I don't cast it, it does not work.
    – Zanders
    Apr 30, 2013 at 14:44
  • That doesn't matter with the PHP driver, dicts and arrays are analogous (as you stated) and the PHP driver can encode to the correct notation regardless. What MongoDB version are you on? The $slice operator is very new (v2.4.3) so it seems that this is what is happening, MongoDB is reading this as a normal document because it doesn't understand the operators you have put in
    – Sammaye
    Apr 30, 2013 at 14:58

1 Answer 1

0

You are running MongoDB pre 2.4.

MongoDB 2.4 introduced the $slice, and previous the $push operator did not support the $each operator.

When MongoDB encounters an unrecognised operators like this (i.e. in MongoDB 2.2) for $push it will believe it is actually the keys you want to use and treat it like any other data.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.