天天看點

MongoDB批量更新

 public void bulkOps(List<T> ts)

    {

        BulkOperations ops = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, collectionName());

        for (T   t: ts)

        {

            Query query = new Query();

            query.addCriteria(Criteria.where("_id").is(t.getId()));

            Update update = buildUpdate(t);

            ops.upsert(query, update);

        }

        ops.execute();

    }

    private Update buildUpdate(T t)

    {

        Update update = new Update();

        Field[] fields = UserBehavior.class.getDeclaredFields();

        for (int i = 0; i < fields.length; i++)

        {

            fields[i].setAccessible(true);

            String fieldName = fields[i].getName();

            UpsertConfig column = fields[i].getAnnotation(UpsertConfig.class);

            if (column == null)

            {

                continue;

            }

            String key = StringUtils.isNotEmpty(column.name()) ? column.name() : fieldName;

            Object value = null;

            try

            {

                value = fields[i].get(userBehavior);

            }

            catch (IllegalAccessException e)

            {

                log.error("buildUpdate get FieldName {} error {} ", key, e);

            }

            update.set(key, value);

        }

        return update;

    }