title: MongoDB update command retain first and last element of an array field
body: <p>I have a scenario where I'd like to be able to remove all elements except the first and the last (by position in the array) from an array field in all documents in a mongo collection matching a certain query. I've tried the following command which only retains the first element:</p>
  
  <pre><code>db.collection.update(*query*,
  {
    $push : {
       arrayField : {
         $each : [],
         $slice : 1,
         $slice : -1
       }
    }
  },
  {
    multi : true
  })
  </code></pre>
  
  <p>Unfortunately I don't think what I want to achieve is possible using a simple update.</p>
  
  <p>Ultimately I am going to be orchestrating this this with a java client application using the mongo java driver and I don't want to have to retrieve all the documents, modify them appropriately and then persist the changes. </p>
  
  <p>Any ideas for a solution which will run on the server?</p>