AggregateMongoItemReader to perform mongoDb aggregations

for a work project i needed to perform aggregations in mongodb using spring batch, so a MongoItemReader which enables to perform aggregations using the aggregation framework. The idea is to use this reader whenever there is the need to aggregate data from mongoDB collections in reader phase.

I needed this feature because of the fact that i needed to merge data from 2 different collections, and doing so in reader phase made all the following steps (processing and writing) easier because the data are already aggregated and ready to be processed. I created this custom reader but i have some concerns related to the concurrency and chunk processing (during testing phase i did not found any issue) and also if i can follow other paths to accomplish the same result. Any feedback is appreciated, thanks

import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import lombok.Setter;
import org.springframework.batch.item.data.MongoItemReader;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;

@Setter
public class AggregationMongoItemReader<T> extends MongoItemReader<T> {

    private MongoOperations mongoTemplate;
    private Aggregation aggregation;
    private Class<T> classType;
    private String collection;
    private int pageSize = 5; //Must be same size of chunk to avoid reprocessing?
    private volatile AtomicInteger currentPage = new AtomicInteger(0);

    @Override
    protected Iterator<T> doPageRead() {

        int skip = currentPage.getAndIncrement() * pageSize;

        List<AggregationOperation> stages = new ArrayList<>(aggregation.getPipeline().getOperations());
        stages.add(Aggregation.skip((long) skip));
        stages.add(Aggregation.limit(pageSize));
        Aggregation limitedAggregation = Aggregation.newAggregation(stages);

        AggregationResults<T> results = mongoTemplate.aggregate(limitedAggregation, collection, classType);
        List<T> mappedResults = results.getMappedResults();

        if (mappedResults.isEmpty()) {
            return Collections.emptyIterator();
        }

        return mappedResults.iterator();
    }

    @Override
    protected void doOpen() throws Exception {
        super.doOpen();
    }

    @Override
    protected void doClose() throws Exception {
        super.doClose();
    }
}

Example of usage

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.data.MongoItemReader;
import org.springframework.batch.item.support.SynchronizedItemStreamReader;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.ArrayOperators;
import org.springframework.data.mongodb.core.aggregation.ComparisonOperators;
import org.springframework.data.mongodb.core.aggregation.ConditionalOperators;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@RequiredArgsConstructor
public class CertificationsReader {

    private final MongoTemplate mongoTemplate;

    public ItemReader<Certification> certificationReader() {
        SynchronizedItemStreamReader<Certification> synchronizedItemStreamReader = new SynchronizedItemStreamReader<>();
        MongoItemReader<Certification> itemReader = getCertification(certificationType, ledger);
        synchronizedItemStreamReader.setDelegate(itemReader);
        return synchronizedItemStreamReader;
    }

    private MongoItemReader<Certification> getCertification(String certificationType, String ledger) {
        AggregationMongoItemReader<Certification> reader = new AggregationMongoItemReader<>();

        Aggregation aggregation = Aggregation.newAggregation(
            // $lookup stage
            Aggregation.lookup("certifications", "idCertification", "_id", "certification"),
            // $addFields stage
            Aggregation.addFields()
                .addField("certification")
                .withValueOf(ArrayOperators.ArrayElemAt.arrayOf("$certification").elementAt(0))
                .build(),
            // $match stage
            Aggregation.match(
                Criteria.where("certification.ledger").is(ledger)
                    .and("certification.certificationType").is(certificationType)
                    .and("certification.flagStatus").is("TD")
                    .and("certification.flagLocked").is("0")
            ),
            // $group stage
            Aggregation.group("$idCertification")
                .sum(
                    ConditionalOperators.Cond.when(ComparisonOperators.Eq.valueOf("$certificationResult").equalToValue("OK"))
                        .then(1)
                        .otherwise(0)
                ).as("ok")
                .sum(
                    ConditionalOperators.Cond.when(ComparisonOperators.Eq.valueOf("$certificationResult").equalToValue("KO"))
                        .then(1)
                        .otherwise(0)
                ).as("ko")
                .count().as("total")
                .addToSet("accountId").as("accounts"),
            // $project stage
            Aggregation.project("_id",
                                "ok",
                                "ko",
                                "total",
                                "accounts")
        );

        reader.setMongoTemplate(mongoTemplate);
        reader.setCollection("simulations");
        reader.setAggregation(aggregation);
        reader.setClassType(Certification.class);
        return reader;
    }
}

New contributor

Gaetano is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật