Skip to content

Multiple records updating throws optimistic locking in mongo #618

@hkg25

Description

@hkg25

I have a daily scheduled grails job which updates the properties of users with changes from last date. It goes like this

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()
    }

UserService

void updateStatsForAllUsers(DateTime date) {
    List<User> customers = User.list()
    List<Order> orders = null
    customers.each { customer ->
        orders = customer.orders?.findAll{it.status.equals("DELIVERED")}?.sort{it?.dateCreated}
        if (orders?.size() > 0) {
            customer.firstOrderDate = orders?.first()?.dateCreated
            customer.lastOrderDate = orders?.last()?.dateCreated
            customer.totalOrders = orders.size()
            customer.save(flush: true)
        }
    }
}

i am not able to understand that the loop is updating different objects , then why does it throws optimistic lock exception, 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions