Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

[MongoDB Spring Boot] How to Union all two collection a and b not relationship?


May 02, 2021 Programing language



I using MongoDB 4.2.

Therefore, to solve this problem.

MongoDB query

db.collectionA.aggregate([{
    $group: {"_id": null, "first": { $push: "$$ROOT"}}}, {
    $lookup: {from: "collectionB",pipeline: [ { $match: {} } ],as: "second"}},
    {
    $project: {"all": { $concatArrays: [ "$first", "$second" ]}}}
    ,{
    $unwind: "$all"}, {
    $replaceRoot: { "newRoot": "$all" }}
])

Spring Boot:

First we will injection MongoTemplate.

@Autowired
private MongoTemplate mongoTemplate;

Second, we write funtion to get collection out you want by MappedResult.

List<AggregationOperation> operations = new ArrayList();
operations.add(Aggregation.group().push("$$ROOT").as("first"));
operations.add(Aggregation.lookup("collectionB", "id", "id","second"));
operations.add(Aggregation.project().and("first").concatArrays("second").as("all"));
operations.add(Aggregation.unwind("all"));
operations.add(Aggregation.replaceRoot("all"));

The code above the "lookup" does not soundly correct, but it ran for me.

Aggregation.newAggregation(CollectionA.class, operations);
List<CollectionOutResponse> results = mongoTemplate.aggregate(aggregation, CollectionOutResponse.class).getMappedResults();

if you want use page for you respone. You can consult:

PageRequest pageRequest = // write your funtion get PageRequest.of. ex: getPageable(size, page, sort);

int total = mongoTemplate.aggregate(aggregation, CollectionOutResponse.class).getMappedResults().size();

Page<CollectionOutResponse> response = new PageImpl<>(results, pageRequest, total);