/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/LimitOperation.java

https://github.com/spring-projects/spring-data-mongodb · Java · 55 lines · 18 code · 7 blank · 30 comment · 0 complexity · fa56b8ff027b2e674dffc9db5c7f1bed MD5 · raw file

  1. /*
  2. * Copyright 2013-2022 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * https://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.springframework.data.mongodb.core.aggregation;
  17. import org.bson.Document;
  18. import org.springframework.util.Assert;
  19. /**
  20. * Encapsulates the {@code $limit}-operation.
  21. * <p>
  22. * We recommend to use the static factory method {@link Aggregation#limit(long)} instead of creating instances of this
  23. * class directly.
  24. *
  25. * @author Thomas Darimont
  26. * @author Oliver Gierke
  27. * @author Christoph Strobl
  28. * @since 1.3
  29. * @see <a href="https://docs.mongodb.org/manual/reference/aggregation/limit/">MongoDB Aggregation Framework: $limit</a>
  30. */
  31. public class LimitOperation implements AggregationOperation {
  32. private final long maxElements;
  33. /**
  34. * @param maxElements Number of documents to consider.
  35. */
  36. public LimitOperation(long maxElements) {
  37. Assert.isTrue(maxElements >= 0, "Maximum number of elements must be greater or equal to zero");
  38. this.maxElements = maxElements;
  39. }
  40. @Override
  41. public Document toDocument(AggregationOperationContext context) {
  42. return new Document(getOperator(), Long.valueOf(maxElements));
  43. }
  44. @Override
  45. public String getOperator() {
  46. return "$limit";
  47. }
  48. }