I'm trying to make a query to find all with limit 1, using the @Query annotation in Java, but I can't find any answer

Specifically, I need to make a query that has only one request, it is a find all but that has a limit of one with the Springboot @Query annotation, I have tried every way but I still haven’t found a solution

Hi @Andres_Felipe_Calderon_Sarmiento! Welcome to the community forum! :star:

The @Query annotation expects only the parameters defined in the documentation. To utilize limit functionality, you can leverage the available operators in MongoDB.

I attempted to write the following code using the sample dataset from the collection sample_supplies.sales collection.

@Override
public Stream<Sales> getSingleSale() {
    Stream<Sales> optionalSales =  salesRepository.findAll().stream().limit(1);
    return optionalSales;
}

@Override
public Sales getSaleByLocation(String location) {
    Query query = new Query();
    query.addCriteria(Criteria.where("storeLocation").is(location));
    query.limit(1);
    return mongoTemplate.findOne(query, Sales.class);
}

Please let us know if this code snippet meets your requirements.

Best regards,
Aasawari