SpringBoot With MongoRepository

Hi,

I’m using Spring Boot with MongoDB.

I have repository like this:

List<PackageHoliday> findPackageHolidayByTypeOfPackageHolidayContains(String typeOfPackageHoliday);

And Controller like this

  @GetMapping("/escortedTours")
    public List<PackageHoliday> escortedToursNested() {
        return packageHolidayRepository.findPackageHolidayByTypeOfPackageHolidayContains("escortedTours");
    }

As you can see, program is returning a list of elements that has typeOfPackeHoliday == escortedTours.

But that return me all elements with that type while I want to return just one random from collection. How I can create method that will return me one random element from collection that have typeOfPackageHoliday == escortedTours

Hello @Sefan_Jankovic, welcome to the MongoDB Community forum!

You can try this aggregation:

From the shell:

db.collection.aggregate([
{ 
  $match: { typeOfPackageHoliday: "escortedTours" } 
},
{ 
  $sample: { size: 1 } 
},
])

Using Spring Data MongoDB’s MongoRepository API - in your repository interface define a method like this:

String matchStage = "{ '$match': { 'typeOfPackageHoliday': { '$eq':  ?0  } } }";
String sampleStage = "{ '$sample' : { 'size' : 1 } }";
String aggPipeline = matchStage + ", " + sampleStage;

@Aggregation(pipeline = { aggPipeline } )
List<PackageHoliday> findByTypeOfPackageHoliday(String typeOfPackageHoliday);

And, you call the repository method as:

String inputType = "escortedTours";
List<PackageHoliday> result = packageHolidayRepository.findByTypeOfPackageHoliday(inputType);
1 Like