Imagine I have three documents in collection:
First one is:
Title: Myanmar
Category: escortedTours
Second one is:
Title: Barcelona
Category: independentTours
Third one is:
Title: Spain
Category: escortedTours
Now I want to create a method that will return me just ONE RANDOM document with category
as escortedTours
. So for every refresh page program need to return me one random document with escortedTours
.
I create something like this but this return me all documents with category
as escortedTours
while I need one random element on every refresh.
Repo:
List<PackageHoliday> findByTypeOfPackageHoliday(String typeOfPackageHoliday);
ServiceImpl:
@Override
public List<PackageHoliday> findByTypeOfPackageHoliday(String typeOfPackageHoliday) {
return packageHolidayRepository.findByTypeOfPackageHoliday(typeOfPackageHoliday);
}
And controller:
@GetMapping("/getEscortedTours")
public List<PackageHoliday> getByPackageHoliday() {
return packageHolidayService.findByTypeOfPackageHoliday("escortedTours");
}
What and where I need to add/create so this will return me just one random document from collection with category as escortedTours
Try the $sample operator:
db.PackageHoliday.aggregate([
{
"$match": {
Category: "escortedTours"
}
},
{
$sample: {
size: 1
}
}
])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.