title: Grails MongoDB Optimistic Locking in updating all records
body: <p>I have a daily scheduled grails job which updates the properties of users with changes from last date. It goes like this</p>
  
  <pre><code>try {
          // Daily job for updating user orders
          DateTime yesterday = new DateTime().withZone(DateTimeZone.getDefault()).withTimeAtStartOfDay().minusDays(1)
          userService.updateStatsForAllUsers(yesterday)
      }
      catch (Exception e) {
          println e.getCause()
      }
  </code></pre>
  
  <p>UserService</p>
  
  <pre><code>void updateStatsForAllUsers(DateTime date) {
      List&lt;User&gt; customers = User.list()
      List&lt;Order&gt; orders = null
      customers.each { customer -&gt;
          orders = customer.orders?.findAll{it.status.equals("DELIVERED")}?.sort{it?.dateCreated}
          if (orders?.size() &gt; 0) {
              customer.firstOrderDate = orders?.first()?.dateCreated
              customer.lastOrderDate = orders?.last()?.dateCreated
              customer.totalOrders = orders.size()
              customer.save(flush: true)
          }
      }
  }
  </code></pre>
  
  <p>We have a user base of around 50k, and this job always throws a OptimisticLockingException on user save., how can we handle this, is there any way for such batch update using grails mongo.</p>