PageRenderTime 50ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

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

http://github.com/SpringSource/spring-data-mongodb
Java | 1620 lines | 217 code | 117 blank | 1286 comment | 2 complexity | 6f9060a3917ae48473bb637eeb4c3a7a MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. /*
  2. * Copyright 2011-2021 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;
  17. import java.util.Collection;
  18. import java.util.List;
  19. import java.util.Set;
  20. import java.util.function.Consumer;
  21. import java.util.function.Supplier;
  22. import org.bson.Document;
  23. import org.springframework.data.geo.GeoResults;
  24. import org.springframework.data.mongodb.core.BulkOperations.BulkMode;
  25. import org.springframework.data.mongodb.core.aggregation.Aggregation;
  26. import org.springframework.data.mongodb.core.aggregation.AggregationOptions;
  27. import org.springframework.data.mongodb.core.aggregation.AggregationResults;
  28. import org.springframework.data.mongodb.core.aggregation.AggregationUpdate;
  29. import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
  30. import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
  31. import org.springframework.data.mongodb.core.convert.MongoConverter;
  32. import org.springframework.data.mongodb.core.index.IndexOperations;
  33. import org.springframework.data.mongodb.core.mapreduce.GroupBy;
  34. import org.springframework.data.mongodb.core.mapreduce.GroupByResults;
  35. import org.springframework.data.mongodb.core.mapreduce.MapReduceOptions;
  36. import org.springframework.data.mongodb.core.mapreduce.MapReduceResults;
  37. import org.springframework.data.mongodb.core.query.BasicQuery;
  38. import org.springframework.data.mongodb.core.query.Criteria;
  39. import org.springframework.data.mongodb.core.query.NearQuery;
  40. import org.springframework.data.mongodb.core.query.Query;
  41. import org.springframework.data.mongodb.core.query.Update;
  42. import org.springframework.data.mongodb.core.query.UpdateDefinition;
  43. import org.springframework.data.util.CloseableIterator;
  44. import org.springframework.lang.Nullable;
  45. import org.springframework.util.Assert;
  46. import org.springframework.util.ClassUtils;
  47. import com.mongodb.ClientSessionOptions;
  48. import com.mongodb.ReadPreference;
  49. import com.mongodb.client.ClientSession;
  50. import com.mongodb.client.MongoCollection;
  51. import com.mongodb.client.result.DeleteResult;
  52. import com.mongodb.client.result.UpdateResult;
  53. /**
  54. * Interface that specifies a basic set of MongoDB operations. Implemented by {@link MongoTemplate}. Not often used but
  55. * a useful option for extensibility and testability (as it can be easily mocked, stubbed, or be the target of a JDK
  56. * proxy).
  57. * <br />
  58. * <strong>NOTE:</strong> Some operations cannot be executed within a MongoDB transaction. Please refer to the MongoDB
  59. * specific documentation to learn more about <a href="https://docs.mongodb.com/manual/core/transactions/">Multi
  60. * Document Transactions</a>.
  61. *
  62. * @author Thomas Risberg
  63. * @author Mark Pollack
  64. * @author Oliver Gierke
  65. * @author Tobias Trelle
  66. * @author Chuong Ngo
  67. * @author Christoph Strobl
  68. * @author Thomas Darimont
  69. * @author Maninder Singh
  70. * @author Mark Paluch
  71. */
  72. public interface MongoOperations extends FluentMongoOperations {
  73. /**
  74. * The collection name used for the specified class by this template.
  75. *
  76. * @param entityClass must not be {@literal null}.
  77. * @return never {@literal null}.
  78. */
  79. String getCollectionName(Class<?> entityClass);
  80. /**
  81. * Execute the a MongoDB command expressed as a JSON string. Parsing is delegated to {@link Document#parse(String)} to
  82. * obtain the {@link Document} holding the actual command. Any errors that result from executing this command will be
  83. * converted into Spring's DAO exception hierarchy.
  84. *
  85. * @param jsonCommand a MongoDB command expressed as a JSON string. Must not be {@literal null}.
  86. * @return a result object returned by the action.
  87. */
  88. Document executeCommand(String jsonCommand);
  89. /**
  90. * Execute a MongoDB command. Any errors that result from executing this command will be converted into Spring's DAO
  91. * exception hierarchy.
  92. *
  93. * @param command a MongoDB command.
  94. * @return a result object returned by the action.
  95. */
  96. Document executeCommand(Document command);
  97. /**
  98. * Execute a MongoDB command. Any errors that result from executing this command will be converted into Spring's data
  99. * access exception hierarchy.
  100. *
  101. * @param command a MongoDB command, must not be {@literal null}.
  102. * @param readPreference read preferences to use, can be {@literal null}.
  103. * @return a result object returned by the action.
  104. * @since 1.7
  105. */
  106. Document executeCommand(Document command, @Nullable ReadPreference readPreference);
  107. /**
  108. * Execute a MongoDB query and iterate over the query results on a per-document basis with a DocumentCallbackHandler.
  109. *
  110. * @param query the query class that specifies the criteria used to find a record and also an optional fields
  111. * specification. Must not be {@literal null}.
  112. * @param collectionName name of the collection to retrieve the objects from.
  113. * @param dch the handler that will extract results, one document at a time.
  114. */
  115. void executeQuery(Query query, String collectionName, DocumentCallbackHandler dch);
  116. /**
  117. * Executes a {@link DbCallback} translating any exceptions as necessary.
  118. * <br />
  119. * Allows for returning a result object, that is a domain object or a collection of domain objects.
  120. *
  121. * @param action callback object that specifies the MongoDB actions to perform on the passed in DB instance. Must not
  122. * be {@literal null}.
  123. * @param <T> return type.
  124. * @return a result object returned by the action or {@literal null}.
  125. */
  126. @Nullable
  127. <T> T execute(DbCallback<T> action);
  128. /**
  129. * Executes the given {@link CollectionCallback} on the entity collection of the specified class.
  130. * <br />
  131. * Allows for returning a result object, that is a domain object or a collection of domain objects.
  132. *
  133. * @param entityClass class that determines the collection to use. Must not be {@literal null}.
  134. * @param action callback object that specifies the MongoDB action. Must not be {@literal null}.
  135. * @param <T> return type.
  136. * @return a result object returned by the action or {@literal null}.
  137. */
  138. @Nullable
  139. <T> T execute(Class<?> entityClass, CollectionCallback<T> action);
  140. /**
  141. * Executes the given {@link CollectionCallback} on the collection of the given name.
  142. * <br />
  143. * Allows for returning a result object, that is a domain object or a collection of domain objects.
  144. *
  145. * @param collectionName the name of the collection that specifies which {@link MongoCollection} instance will be
  146. * passed into. Must not be {@literal null} or empty.
  147. * @param action callback object that specifies the MongoDB action the callback action. Must not be {@literal null}.
  148. * @param <T> return type.
  149. * @return a result object returned by the action or {@literal null}.
  150. */
  151. @Nullable
  152. <T> T execute(String collectionName, CollectionCallback<T> action);
  153. /**
  154. * Obtain a {@link ClientSession session} bound instance of {@link SessionScoped} binding a new {@link ClientSession}
  155. * with given {@literal sessionOptions} to each and every command issued against MongoDB.
  156. *
  157. * @param sessionOptions must not be {@literal null}.
  158. * @return new instance of {@link SessionScoped}. Never {@literal null}.
  159. * @since 2.1
  160. */
  161. SessionScoped withSession(ClientSessionOptions sessionOptions);
  162. /**
  163. * Obtain a {@link ClientSession session} bound instance of {@link SessionScoped} binding the {@link ClientSession}
  164. * provided by the given {@link Supplier} to each and every command issued against MongoDB.
  165. * <br />
  166. * <strong>Note:</strong> It is up to the caller to manage the {@link ClientSession} lifecycle. Use the
  167. * {@link SessionScoped#execute(SessionCallback, Consumer)} hook to potentially close the {@link ClientSession}.
  168. *
  169. * @param sessionProvider must not be {@literal null}.
  170. * @since 2.1
  171. */
  172. default SessionScoped withSession(Supplier<ClientSession> sessionProvider) {
  173. Assert.notNull(sessionProvider, "SessionProvider must not be null!");
  174. return new SessionScoped() {
  175. private final Object lock = new Object();
  176. private @Nullable ClientSession session = null;
  177. @Override
  178. public <T> T execute(SessionCallback<T> action, Consumer<ClientSession> onComplete) {
  179. synchronized (lock) {
  180. if (session == null) {
  181. session = sessionProvider.get();
  182. }
  183. }
  184. try {
  185. return action.doInSession(MongoOperations.this.withSession(session));
  186. } finally {
  187. onComplete.accept(session);
  188. }
  189. }
  190. };
  191. }
  192. /**
  193. * Obtain a {@link ClientSession} bound instance of {@link MongoOperations}.
  194. * <br />
  195. * <strong>Note:</strong> It is up to the caller to manage the {@link ClientSession} lifecycle.
  196. *
  197. * @param session must not be {@literal null}.
  198. * @return {@link ClientSession} bound instance of {@link MongoOperations}.
  199. * @since 2.1
  200. */
  201. MongoOperations withSession(ClientSession session);
  202. /**
  203. * Executes the given {@link Query} on the entity collection of the specified {@code entityType} backed by a Mongo DB
  204. * {@link com.mongodb.client.FindIterable}.
  205. * <p>
  206. * Returns a {@link CloseableIterator} that wraps the a Mongo DB {@link com.mongodb.client.FindIterable} that needs to
  207. * be closed.
  208. *
  209. * @param query the query class that specifies the criteria used to find a record and also an optional fields
  210. * specification. Must not be {@literal null}.
  211. * @param entityType must not be {@literal null}.
  212. * @param <T> element return type
  213. * @return will never be {@literal null}.
  214. * @since 1.7
  215. */
  216. <T> CloseableIterator<T> stream(Query query, Class<T> entityType);
  217. /**
  218. * Executes the given {@link Query} on the entity collection of the specified {@code entityType} and collection backed
  219. * by a Mongo DB {@link com.mongodb.client.FindIterable}.
  220. * <p>
  221. * Returns a {@link CloseableIterator} that wraps the a Mongo DB {@link com.mongodb.client.FindIterable} that needs to
  222. * be closed.
  223. *
  224. * @param query the query class that specifies the criteria used to find a record and also an optional fields
  225. * specification. Must not be {@literal null}.
  226. * @param entityType must not be {@literal null}.
  227. * @param collectionName must not be {@literal null} or empty.
  228. * @param <T> element return type
  229. * @return will never be {@literal null}.
  230. * @since 1.10
  231. */
  232. <T> CloseableIterator<T> stream(Query query, Class<T> entityType, String collectionName);
  233. /**
  234. * Create an uncapped collection with a name based on the provided entity class.
  235. *
  236. * @param entityClass class that determines the collection to create.
  237. * @return the created collection.
  238. */
  239. <T> MongoCollection<Document> createCollection(Class<T> entityClass);
  240. /**
  241. * Create a collection with a name based on the provided entity class using the options.
  242. *
  243. * @param entityClass class that determines the collection to create. Must not be {@literal null}.
  244. * @param collectionOptions options to use when creating the collection.
  245. * @return the created collection.
  246. */
  247. <T> MongoCollection<Document> createCollection(Class<T> entityClass, @Nullable CollectionOptions collectionOptions);
  248. /**
  249. * Create an uncapped collection with the provided name.
  250. *
  251. * @param collectionName name of the collection.
  252. * @return the created collection.
  253. */
  254. MongoCollection<Document> createCollection(String collectionName);
  255. /**
  256. * Create a collection with the provided name and options.
  257. *
  258. * @param collectionName name of the collection. Must not be {@literal null} nor empty.
  259. * @param collectionOptions options to use when creating the collection.
  260. * @return the created collection.
  261. */
  262. MongoCollection<Document> createCollection(String collectionName, @Nullable CollectionOptions collectionOptions);
  263. /**
  264. * A set of collection names.
  265. *
  266. * @return list of collection names.
  267. */
  268. Set<String> getCollectionNames();
  269. /**
  270. * Get a {@link MongoCollection} by its name. The returned collection may not exists yet (except in local memory) and
  271. * is created on first interaction with the server. Collections can be explicitly created via
  272. * {@link #createCollection(Class)}. Please make sure to check if the collection {@link #collectionExists(Class)
  273. * exists} first.
  274. * <br />
  275. * Translate any exceptions as necessary.
  276. *
  277. * @param collectionName name of the collection. Must not be {@literal null}.
  278. * @return an existing collection or one created on first server interaction.
  279. */
  280. MongoCollection<Document> getCollection(String collectionName);
  281. /**
  282. * Check to see if a collection with a name indicated by the entity class exists.
  283. * <br />
  284. * Translate any exceptions as necessary.
  285. *
  286. * @param entityClass class that determines the name of the collection. Must not be {@literal null}.
  287. * @return true if a collection with the given name is found, false otherwise.
  288. */
  289. <T> boolean collectionExists(Class<T> entityClass);
  290. /**
  291. * Check to see if a collection with a given name exists.
  292. * <br />
  293. * Translate any exceptions as necessary.
  294. *
  295. * @param collectionName name of the collection. Must not be {@literal null}.
  296. * @return true if a collection with the given name is found, false otherwise.
  297. */
  298. boolean collectionExists(String collectionName);
  299. /**
  300. * Drop the collection with the name indicated by the entity class.
  301. * <br />
  302. * Translate any exceptions as necessary.
  303. *
  304. * @param entityClass class that determines the collection to drop/delete. Must not be {@literal null}.
  305. */
  306. <T> void dropCollection(Class<T> entityClass);
  307. /**
  308. * Drop the collection with the given name.
  309. * <br />
  310. * Translate any exceptions as necessary.
  311. *
  312. * @param collectionName name of the collection to drop/delete.
  313. */
  314. void dropCollection(String collectionName);
  315. /**
  316. * Returns the operations that can be performed on indexes
  317. *
  318. * @return index operations on the named collection
  319. */
  320. IndexOperations indexOps(String collectionName);
  321. /**
  322. * Returns the operations that can be performed on indexes
  323. *
  324. * @return index operations on the named collection associated with the given entity class
  325. */
  326. IndexOperations indexOps(Class<?> entityClass);
  327. /**
  328. * Returns the {@link ScriptOperations} that can be performed on {@link com.mongodb.client.MongoDatabase} level.
  329. *
  330. * @return never {@literal null}.
  331. * @since 1.7
  332. * @deprecated since 2.2. The {@code eval} command has been removed without replacement in MongoDB Server 4.2.0.
  333. */
  334. @Deprecated
  335. ScriptOperations scriptOps();
  336. /**
  337. * Returns a new {@link BulkOperations} for the given collection. <br />
  338. * <strong>NOTE:</strong> Any additional support for field mapping, etc. is not available for {@literal update} or
  339. * {@literal remove} operations in bulk mode due to the lack of domain type information. Use
  340. * {@link #bulkOps(BulkMode, Class, String)} to get full type specific support.
  341. *
  342. * @param mode the {@link BulkMode} to use for bulk operations, must not be {@literal null}.
  343. * @param collectionName the name of the collection to work on, must not be {@literal null} or empty.
  344. * @return {@link BulkOperations} on the named collection
  345. */
  346. BulkOperations bulkOps(BulkMode mode, String collectionName);
  347. /**
  348. * Returns a new {@link BulkOperations} for the given entity type.
  349. *
  350. * @param mode the {@link BulkMode} to use for bulk operations, must not be {@literal null}.
  351. * @param entityType the name of the entity class, must not be {@literal null}.
  352. * @return {@link BulkOperations} on the named collection associated of the given entity class.
  353. */
  354. BulkOperations bulkOps(BulkMode mode, Class<?> entityType);
  355. /**
  356. * Returns a new {@link BulkOperations} for the given entity type and collection name.
  357. *
  358. * @param mode the {@link BulkMode} to use for bulk operations, must not be {@literal null}.
  359. * @param entityType the name of the entity class. Can be {@literal null}.
  360. * @param collectionName the name of the collection to work on, must not be {@literal null} or empty.
  361. * @return {@link BulkOperations} on the named collection associated with the given entity class.
  362. */
  363. BulkOperations bulkOps(BulkMode mode, @Nullable Class<?> entityType, String collectionName);
  364. /**
  365. * Query for a list of objects of type T from the collection used by the entity class.
  366. * <br />
  367. * The object is converted from the MongoDB native representation using an instance of {@see MongoConverter}. Unless
  368. * configured otherwise, an instance of {@link MappingMongoConverter} will be used.
  369. * <br />
  370. * If your collection does not contain a homogeneous collection of types, this operation will not be an efficient way
  371. * to map objects since the test for class type is done in the client and not on the server.
  372. *
  373. * @param entityClass the parametrized type of the returned list.
  374. * @return the converted collection.
  375. */
  376. <T> List<T> findAll(Class<T> entityClass);
  377. /**
  378. * Query for a list of objects of type T from the specified collection.
  379. * <br />
  380. * The object is converted from the MongoDB native representation using an instance of {@see MongoConverter}. Unless
  381. * configured otherwise, an instance of {@link MappingMongoConverter} will be used.
  382. * <br />
  383. * If your collection does not contain a homogeneous collection of types, this operation will not be an efficient way
  384. * to map objects since the test for class type is done in the client and not on the server.
  385. *
  386. * @param entityClass the parametrized type of the returned list.
  387. * @param collectionName name of the collection to retrieve the objects from.
  388. * @return the converted collection.
  389. */
  390. <T> List<T> findAll(Class<T> entityClass, String collectionName);
  391. /**
  392. * Execute a group operation over the entire collection. The group operation entity class should match the 'shape' of
  393. * the returned object that takes int account the initial document structure as well as any finalize functions.
  394. *
  395. * @param inputCollectionName the collection where the group operation will read from
  396. * @param groupBy the conditions under which the group operation will be performed, e.g. keys, initial document,
  397. * reduce function.
  398. * @param entityClass The parametrized type of the returned list
  399. * @return The results of the group operation
  400. * @deprecated since 2.2. The {@code group} command has been removed in MongoDB Server 4.2.0. <br />
  401. * Please use {@link #aggregate(TypedAggregation, String, Class) } with a
  402. * {@link org.springframework.data.mongodb.core.aggregation.GroupOperation} instead.
  403. */
  404. @Deprecated
  405. <T> GroupByResults<T> group(String inputCollectionName, GroupBy groupBy, Class<T> entityClass);
  406. /**
  407. * Execute a group operation restricting the rows to those which match the provided Criteria. The group operation
  408. * entity class should match the 'shape' of the returned object that takes int account the initial document structure
  409. * as well as any finalize functions.
  410. *
  411. * @param criteria The criteria that restricts the row that are considered for grouping. If not specified all rows are
  412. * considered.
  413. * @param inputCollectionName the collection where the group operation will read from
  414. * @param groupBy the conditions under which the group operation will be performed, e.g. keys, initial document,
  415. * reduce function.
  416. * @param entityClass The parametrized type of the returned list
  417. * @return The results of the group operation
  418. * @deprecated since 2.2. The {@code group} command has been removed in MongoDB Server 4.2.0. <br />
  419. * Please use {@link #aggregate(TypedAggregation, String, Class) } with a
  420. * {@link org.springframework.data.mongodb.core.aggregation.GroupOperation} and
  421. * {@link org.springframework.data.mongodb.core.aggregation.MatchOperation} instead.
  422. */
  423. @Deprecated
  424. <T> GroupByResults<T> group(@Nullable Criteria criteria, String inputCollectionName, GroupBy groupBy,
  425. Class<T> entityClass);
  426. /**
  427. * Execute an aggregation operation. The raw results will be mapped to the given entity class. The name of the
  428. * inputCollection is derived from the inputType of the aggregation.
  429. *
  430. * @param aggregation The {@link TypedAggregation} specification holding the aggregation operations, must not be
  431. * {@literal null}.
  432. * @param collectionName The name of the input collection to use for the aggreation.
  433. * @param outputType The parametrized type of the returned list, must not be {@literal null}.
  434. * @return The results of the aggregation operation.
  435. * @since 1.3
  436. */
  437. <O> AggregationResults<O> aggregate(TypedAggregation<?> aggregation, String collectionName, Class<O> outputType);
  438. /**
  439. * Execute an aggregation operation. The raw results will be mapped to the given entity class. The name of the
  440. * inputCollection is derived from the inputType of the aggregation.
  441. *
  442. * @param aggregation The {@link TypedAggregation} specification holding the aggregation operations, must not be
  443. * {@literal null}.
  444. * @param outputType The parametrized type of the returned list, must not be {@literal null}.
  445. * @return The results of the aggregation operation.
  446. * @since 1.3
  447. */
  448. <O> AggregationResults<O> aggregate(TypedAggregation<?> aggregation, Class<O> outputType);
  449. /**
  450. * Execute an aggregation operation. The raw results will be mapped to the given entity class.
  451. *
  452. * @param aggregation The {@link Aggregation} specification holding the aggregation operations, must not be
  453. * {@literal null}.
  454. * @param inputType the inputType where the aggregation operation will read from, must not be {@literal null} or
  455. * empty.
  456. * @param outputType The parametrized type of the returned list, must not be {@literal null}.
  457. * @return The results of the aggregation operation.
  458. * @since 1.3
  459. */
  460. <O> AggregationResults<O> aggregate(Aggregation aggregation, Class<?> inputType, Class<O> outputType);
  461. /**
  462. * Execute an aggregation operation. The raw results will be mapped to the given entity class.
  463. *
  464. * @param aggregation The {@link Aggregation} specification holding the aggregation operations, must not be
  465. * {@literal null}.
  466. * @param collectionName the collection where the aggregation operation will read from, must not be {@literal null} or
  467. * empty.
  468. * @param outputType The parametrized type of the returned list, must not be {@literal null}.
  469. * @return The results of the aggregation operation.
  470. * @since 1.3
  471. */
  472. <O> AggregationResults<O> aggregate(Aggregation aggregation, String collectionName, Class<O> outputType);
  473. /**
  474. * Execute an aggregation operation backed by a Mongo DB {@link com.mongodb.client.AggregateIterable}.
  475. * <p>
  476. * Returns a {@link CloseableIterator} that wraps the a Mongo DB {@link com.mongodb.client.AggregateIterable} that
  477. * needs to be closed. The raw results will be mapped to the given entity class. The name of the inputCollection is
  478. * derived from the inputType of the aggregation.
  479. * <p>
  480. * Aggregation streaming can't be used with {@link AggregationOptions#isExplain() aggregation explain}. Enabling
  481. * explanation mode will throw an {@link IllegalArgumentException}.
  482. *
  483. * @param aggregation The {@link TypedAggregation} specification holding the aggregation operations, must not be
  484. * {@literal null}.
  485. * @param collectionName The name of the input collection to use for the aggreation.
  486. * @param outputType The parametrized type of the returned list, must not be {@literal null}.
  487. * @return The results of the aggregation operation.
  488. * @since 2.0
  489. */
  490. <O> CloseableIterator<O> aggregateStream(TypedAggregation<?> aggregation, String collectionName, Class<O> outputType);
  491. /**
  492. * Execute an aggregation operation backed by a Mongo DB {@link com.mongodb.client.AggregateIterable}.
  493. * <br />
  494. * Returns a {@link CloseableIterator} that wraps the a Mongo DB {@link com.mongodb.client.AggregateIterable} that
  495. * needs to be closed. The raw results will be mapped to the given entity class and are returned as stream. The name
  496. * of the inputCollection is derived from the inputType of the aggregation.
  497. * <br />
  498. * Aggregation streaming can't be used with {@link AggregationOptions#isExplain() aggregation explain}. Enabling
  499. * explanation mode will throw an {@link IllegalArgumentException}.
  500. *
  501. * @param aggregation The {@link TypedAggregation} specification holding the aggregation operations, must not be
  502. * {@literal null}.
  503. * @param outputType The parametrized type of the returned list, must not be {@literal null}.
  504. * @return The results of the aggregation operation.
  505. * @since 2.0
  506. */
  507. <O> CloseableIterator<O> aggregateStream(TypedAggregation<?> aggregation, Class<O> outputType);
  508. /**
  509. * Execute an aggregation operation backed by a Mongo DB {@link com.mongodb.client.AggregateIterable}.
  510. * <br />
  511. * Returns a {@link CloseableIterator} that wraps the a Mongo DB {@link com.mongodb.client.AggregateIterable} that
  512. * needs to be closed. The raw results will be mapped to the given entity class.
  513. * <br />
  514. * Aggregation streaming can't be used with {@link AggregationOptions#isExplain() aggregation explain}. Enabling
  515. * explanation mode will throw an {@link IllegalArgumentException}.
  516. *
  517. * @param aggregation The {@link Aggregation} specification holding the aggregation operations, must not be
  518. * {@literal null}.
  519. * @param inputType the inputType where the aggregation operation will read from, must not be {@literal null} or
  520. * empty.
  521. * @param outputType The parametrized type of the returned list, must not be {@literal null}.
  522. * @return The results of the aggregation operation.
  523. * @since 2.0
  524. */
  525. <O> CloseableIterator<O> aggregateStream(Aggregation aggregation, Class<?> inputType, Class<O> outputType);
  526. /**
  527. * Execute an aggregation operation backed by a Mongo DB {@link com.mongodb.client.AggregateIterable}.
  528. * <br />
  529. * Returns a {@link CloseableIterator} that wraps the a Mongo DB {@link com.mongodb.client.AggregateIterable} that
  530. * needs to be closed. The raw results will be mapped to the given entity class.
  531. * <br />
  532. * Aggregation streaming can't be used with {@link AggregationOptions#isExplain() aggregation explain}. Enabling
  533. * explanation mode will throw an {@link IllegalArgumentException}.
  534. *
  535. * @param aggregation The {@link Aggregation} specification holding the aggregation operations, must not be
  536. * {@literal null}.
  537. * @param collectionName the collection where the aggregation operation will read from, must not be {@literal null} or
  538. * empty.
  539. * @param outputType The parametrized type of the returned list, must not be {@literal null}.
  540. * @return The results of the aggregation operation.
  541. * @since 2.0
  542. */
  543. <O> CloseableIterator<O> aggregateStream(Aggregation aggregation, String collectionName, Class<O> outputType);
  544. /**
  545. * Execute a map-reduce operation. The map-reduce operation will be formed with an output type of INLINE
  546. *
  547. * @param inputCollectionName the collection where the map-reduce will read from. Must not be {@literal null}.
  548. * @param mapFunction The JavaScript map function.
  549. * @param reduceFunction The JavaScript reduce function
  550. * @param entityClass The parametrized type of the returned list. Must not be {@literal null}.
  551. * @return The results of the map reduce operation
  552. */
  553. <T> MapReduceResults<T> mapReduce(String inputCollectionName, String mapFunction, String reduceFunction,
  554. Class<T> entityClass);
  555. /**
  556. * Execute a map-reduce operation that takes additional map-reduce options.
  557. *
  558. * @param inputCollectionName the collection where the map-reduce will read from. Must not be {@literal null}.
  559. * @param mapFunction The JavaScript map function
  560. * @param reduceFunction The JavaScript reduce function
  561. * @param mapReduceOptions Options that specify detailed map-reduce behavior.
  562. * @param entityClass The parametrized type of the returned list. Must not be {@literal null}.
  563. * @return The results of the map reduce operation
  564. */
  565. <T> MapReduceResults<T> mapReduce(String inputCollectionName, String mapFunction, String reduceFunction,
  566. @Nullable MapReduceOptions mapReduceOptions, Class<T> entityClass);
  567. /**
  568. * Execute a map-reduce operation that takes a query. The map-reduce operation will be formed with an output type of
  569. * INLINE
  570. *
  571. * @param query The query to use to select the data for the map phase. Must not be {@literal null}.
  572. * @param inputCollectionName the collection where the map-reduce will read from. Must not be {@literal null}.
  573. * @param mapFunction The JavaScript map function
  574. * @param reduceFunction The JavaScript reduce function
  575. * @param entityClass The parametrized type of the returned list. Must not be {@literal null}.
  576. * @return The results of the map reduce operation
  577. */
  578. <T> MapReduceResults<T> mapReduce(Query query, String inputCollectionName, String mapFunction, String reduceFunction,
  579. Class<T> entityClass);
  580. /**
  581. * Execute a map-reduce operation that takes a query and additional map-reduce options
  582. *
  583. * @param query The query to use to select the data for the map phase. Must not be {@literal null}.
  584. * @param inputCollectionName the collection where the map-reduce will read from. Must not be {@literal null}.
  585. * @param mapFunction The JavaScript map function
  586. * @param reduceFunction The JavaScript reduce function
  587. * @param mapReduceOptions Options that specify detailed map-reduce behavior
  588. * @param entityClass The parametrized type of the returned list. Must not be {@literal null}.
  589. * @return The results of the map reduce operation
  590. */
  591. <T> MapReduceResults<T> mapReduce(Query query, String inputCollectionName, String mapFunction, String reduceFunction,
  592. @Nullable MapReduceOptions mapReduceOptions, Class<T> entityClass);
  593. /**
  594. * Returns {@link GeoResults} for all entities matching the given {@link NearQuery}. Will consider entity mapping
  595. * information to determine the collection the query is ran against. Note, that MongoDB limits the number of results
  596. * by default. Make sure to add an explicit limit to the {@link NearQuery} if you expect a particular number of
  597. * results.
  598. * <p>
  599. * MongoDB 4.2 has removed the {@code geoNear} command. This method uses since version 2.2 aggregations and the
  600. * {@code $geoNear} aggregation command to emulate {@code geoNear} command functionality. We recommend using
  601. * aggregations directly:
  602. * </p>
  603. *
  604. * <pre class="code">
  605. * TypedAggregation&lt;T&gt; geoNear = TypedAggregation.newAggregation(entityClass, Aggregation.geoNear(near, "dis"))
  606. * .withOptions(AggregationOptions.builder().collation(near.getCollation()).build());
  607. * AggregationResults&lt;Document&gt; results = aggregate(geoNear, Document.class);
  608. * </pre>
  609. *
  610. * @param near must not be {@literal null}.
  611. * @param entityClass must not be {@literal null}.
  612. * @return
  613. * @deprecated since 2.2. The {@code eval} command has been removed in MongoDB Server 4.2.0. Use Aggregations with
  614. * {@link Aggregation#geoNear(NearQuery, String)} instead.
  615. */
  616. @Deprecated
  617. <T> GeoResults<T> geoNear(NearQuery near, Class<T> entityClass);
  618. /**
  619. * Returns {@link GeoResults} for all entities matching the given {@link NearQuery}. Note, that MongoDB limits the
  620. * number of results by default. Make sure to add an explicit limit to the {@link NearQuery} if you expect a
  621. * particular number of results.
  622. * <p>
  623. * MongoDB 4.2 has removed the {@code geoNear} command. This method uses since version 2.2 aggregations and the
  624. * {@code $geoNear} aggregation command to emulate {@code geoNear} command functionality. We recommend using
  625. * aggregations directly:
  626. * </p>
  627. *
  628. * <pre class="code">
  629. * TypedAggregation&lt;T&gt; geoNear = TypedAggregation.newAggregation(entityClass, Aggregation.geoNear(near, "dis"))
  630. * .withOptions(AggregationOptions.builder().collation(near.getCollation()).build());
  631. * AggregationResults&lt;Document&gt; results = aggregate(geoNear, Document.class);
  632. * </pre>
  633. *
  634. * @param near must not be {@literal null}.
  635. * @param entityClass must not be {@literal null}.
  636. * @param collectionName the collection to trigger the query against. If no collection name is given the entity class
  637. * will be inspected. Must not be {@literal null} nor empty.
  638. * @return
  639. * @deprecated since 2.2. The {@code eval} command has been removed in MongoDB Server 4.2.0. Use Aggregations with
  640. * {@link Aggregation#geoNear(NearQuery, String)} instead.
  641. */
  642. @Deprecated
  643. <T> GeoResults<T> geoNear(NearQuery near, Class<T> entityClass, String collectionName);
  644. /**
  645. * Map the results of an ad-hoc query on the collection for the entity class to a single instance of an object of the
  646. * specified type.
  647. * <br />
  648. * The object is converted from the MongoDB native representation using an instance of {@see MongoConverter}. Unless
  649. * configured otherwise, an instance of {@link MappingMongoConverter} will be used.
  650. * <br />
  651. * The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more
  652. * feature rich {@link Query}.
  653. *
  654. * @param query the query class that specifies the criteria used to find a record and also an optional fields
  655. * specification.
  656. * @param entityClass the parametrized type of the returned list.
  657. * @return the converted object.
  658. */
  659. @Nullable
  660. <T> T findOne(Query query, Class<T> entityClass);
  661. /**
  662. * Map the results of an ad-hoc query on the specified collection to a single instance of an object of the specified
  663. * type.
  664. * <br />
  665. * The object is converted from the MongoDB native representation using an instance of {@see MongoConverter}. Unless
  666. * configured otherwise, an instance of {@link MappingMongoConverter} will be used.
  667. * <br />
  668. * The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more
  669. * feature rich {@link Query}.
  670. *
  671. * @param query the query class that specifies the criteria used to find a record and also an optional fields
  672. * specification.
  673. * @param entityClass the parametrized type of the returned list.
  674. * @param collectionName name of the collection to retrieve the objects from.
  675. * @return the converted object.
  676. */
  677. @Nullable
  678. <T> T findOne(Query query, Class<T> entityClass, String collectionName);
  679. /**
  680. * Determine result of given {@link Query} contains at least one element. <br />
  681. * <strong>NOTE:</strong> Any additional support for query/field mapping, etc. is not available due to the lack of
  682. * domain type information. Use {@link #exists(Query, Class, String)} to get full type specific support.
  683. *
  684. * @param query the {@link Query} class that specifies the criteria used to find a record.
  685. * @param collectionName name of the collection to check for objects.
  686. * @return {@literal true} if the query yields a result.
  687. */
  688. boolean exists(Query query, String collectionName);
  689. /**
  690. * Determine result of given {@link Query} contains at least one element.
  691. *
  692. * @param query the {@link Query} class that specifies the criteria used to find a record.
  693. * @param entityClass the parametrized type.
  694. * @return {@literal true} if the query yields a result.
  695. */
  696. boolean exists(Query query, Class<?> entityClass);
  697. /**
  698. * Determine result of given {@link Query} contains at least one element.
  699. *
  700. * @param query the {@link Query} class that specifies the criteria used to find a record.
  701. * @param entityClass the parametrized type. Can be {@literal null}.
  702. * @param collectionName name of the collection to check for objects.
  703. * @return {@literal true} if the query yields a result.
  704. */
  705. boolean exists(Query query, @Nullable Class<?> entityClass, String collectionName);
  706. /**
  707. * Map the results of an ad-hoc query on the collection for the entity class to a List of the specified type.
  708. * <br />
  709. * The object is converted from the MongoDB native representation using an instance of {@see MongoConverter}. Unless
  710. * configured otherwise, an instance of {@link MappingMongoConverter} will be used.
  711. * <br />
  712. * The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more
  713. * feature rich {@link Query}.
  714. *
  715. * @param query the query class that specifies the criteria used to find a record and also an optional fields
  716. * specification. Must not be {@literal null}.
  717. * @param entityClass the parametrized type of the returned list. Must not be {@literal null}.
  718. * @return the List of converted objects.
  719. */
  720. <T> List<T> find(Query query, Class<T> entityClass);
  721. /**
  722. * Map the results of an ad-hoc query on the specified collection to a List of the specified type.
  723. * <br />
  724. * The object is converted from the MongoDB native representation using an instance of {@see MongoConverter}. Unless
  725. * configured otherwise, an instance of {@link MappingMongoConverter} will be used.
  726. * <br />
  727. * The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more
  728. * feature rich {@link Query}.
  729. *
  730. * @param query the query class that specifies the criteria used to find a record and also an optional fields
  731. * specification. Must not be {@literal null}.
  732. * @param entityClass the parametrized type of the returned list. Must not be {@literal null}.
  733. * @param collectionName name of the collection to retrieve the objects from. Must not be {@literal null}.
  734. * @return the List of converted objects.
  735. */
  736. <T> List<T> find(Query query, Class<T> entityClass, String collectionName);
  737. /**
  738. * Returns a document with the given id mapped onto the given class. The collection the query is ran against will be
  739. * derived from the given target class as well.
  740. *
  741. * @param id the id of the document to return. Must not be {@literal null}.
  742. * @param entityClass the type the document shall be converted into. Must not be {@literal null}.
  743. * @return the document with the given id mapped onto the given target class.
  744. */
  745. @Nullable
  746. <T> T findById(Object id, Class<T> entityClass);
  747. /**
  748. * Returns the document with the given id from the given collection mapped onto the given target class.
  749. *
  750. * @param id the id of the document to return.
  751. * @param entityClass the type to convert the document to.
  752. * @param collectionName the collection to query for the document.
  753. * @return he converted object or {@literal null} if document does not exist.
  754. */
  755. @Nullable
  756. <T> T findById(Object id, Class<T> entityClass, String collectionName);
  757. /**
  758. * Finds the distinct values for a specified {@literal field} across a single {@link MongoCollection} or view and
  759. * returns the results in a {@link List}.
  760. *
  761. * @param field the name of the field to inspect for distinct values. Must not be {@literal null}.
  762. * @param entityClass the domain type used for determining the actual {@link MongoCollection}. Must not be
  763. * {@literal null}.
  764. * @param resultClass the result type. Must not be {@literal null}.
  765. * @return never {@literal null}.
  766. * @since 2.1
  767. */
  768. default <T> List<T> findDistinct(String field, Class<?> entityClass, Class<T> resultClass) {
  769. return findDistinct(new Query(), field, entityClass, resultClass);
  770. }
  771. /**
  772. * Finds the distinct values for a specified {@literal field} across a single {@link MongoCollection} or view and
  773. * returns the results in a {@link List}.
  774. *
  775. * @param query filter {@link Query} to restrict search. Must not be {@literal null}.
  776. * @param field the name of the field to inspect for distinct values. Must not be {@literal null}.
  777. * @param entityClass the domain type used for determining the actual {@link MongoCollection} and mapping the
  778. * {@link Query} to the domain type fields. Must not be {@literal null}.
  779. * @param resultClass the result type. Must not be {@literal null}.
  780. * @return never {@literal null}.
  781. * @since 2.1
  782. */
  783. <T> List<T> findDistinct(Query query, String field, Class<?> entityClass, Class<T> resultClass);
  784. /**
  785. * Finds the distinct values for a specified {@literal field} across a single {@link MongoCollection} or view and
  786. * returns the results in a {@link List}.
  787. *
  788. * @param query filter {@link Query} to restrict search. Must not be {@literal null}.
  789. * @param field the name of the field to inspect for distinct values. Must not be {@literal null}.
  790. * @param collectionName the explicit name of the actual {@link MongoCollection}. Must not be {@literal null}.
  791. * @param entityClass the domain type used for mapping the {@link Query} to the domain type fields.
  792. * @param resultClass the result type. Must not be {@literal null}.
  793. * @return never {@literal null}.
  794. * @since 2.1
  795. */
  796. <T> List<T> findDistinct(Query query, String field, String collectionName, Class<?> entityClass,
  797. Class<T> resultClass);
  798. /**
  799. * Finds the distinct values for a specified {@literal field} across a single {@link MongoCollection} or view and
  800. * returns the results in a {@link List}.
  801. *
  802. * @param query filter {@link Query} to restrict search. Must not be {@literal null}.
  803. * @param field the name of the field to inspect for distinct values. Must not be {@literal null}.
  804. * @param collection the explicit name of the actual {@link MongoCollection}. Must not be {@literal null}.
  805. * @param resultClass the result type. Must not be {@literal null}.
  806. * @return never {@literal null}.
  807. * @since 2.1
  808. */
  809. default <T> List<T> findDistinct(Query query, String field, String collection, Class<T> resultClass) {
  810. return findDistinct(query, field, collection, Object.class, resultClass);
  811. }
  812. /**
  813. * Triggers <a href="https://docs.mongodb.org/manual/reference/method/db.collection.findAndModify/">findAndModify </a>
  814. * to apply provided {@link Update} on documents matching {@link Criteria} of given {@link Query}.
  815. *
  816. * @param query the {@link Query} class that specifies the {@link Criteria} used to find a record and also an optional
  817. * fields specification. Must not be {@literal null}.
  818. * @param update the {@link UpdateDefinition} to apply on matching documents. Must not be {@literal null}.
  819. * @param entityClass the parametrized type. Must not be {@literal null}.
  820. * @return the converted object that was updated before it was updated or {@literal null}, if not found.
  821. * @since 3.0
  822. * @see Update
  823. * @see AggregationUpdate
  824. */
  825. @Nullable
  826. <T> T findAndModify(Query query, UpdateDefinition update, Class<T> entityClass);
  827. /**
  828. * Triggers <a href="https://docs.mongodb.org/manual/reference/method/db.collection.findAndModify/">findAndModify </a>
  829. * to apply provided {@link Update} on documents matching {@link Criteria} of given {@link Query}.
  830. *
  831. * @param query the {@link Query} class that specifies the {@link Criteria} used to find a record and also an optional
  832. * fields specification. Must not be {@literal null}.
  833. * @param update the {@link UpdateDefinition} to apply on matching documents. Must not be {@literal null}.
  834. * @param entityClass the parametrized type. Must not be {@literal null}.
  835. * @param collectionName the collection to query. Must not be {@literal null}.
  836. * @return the converted object that was updated before it was updated or {@literal null}, if not found.
  837. * @since 3.0
  838. * @see Update
  839. * @see AggregationUpdate
  840. */
  841. @Nullable
  842. <T> T findAndModify(Query query, UpdateDefinition update, Class<T> entityClass, String collectionName);
  843. /**
  844. * Triggers <a href="https://docs.mongodb.org/manual/reference/method/db.collection.findAndModify/">findAndModify </a>
  845. * to apply provided {@link Update} on documents matching {@link Criteria} of given {@link Query} taking
  846. * {@link FindAndModifyOptions} into account.
  847. *
  848. * @param query the {@link Query} class that specifies the {@link Criteria} used to find a record and also an optional
  849. * fields specification.
  850. * @param update the {@link UpdateDefinition} to apply on matching documents.
  851. * @param options the {@link FindAndModifyOptions} holding additional information.
  852. * @param entityClass the parametrized type.
  853. * @return the converted object that was updated or {@literal null}, if not found. Depending on the value of
  854. * {@link FindAndModifyOptions#isReturnNew()} this will either be the object as it was before the update or as
  855. * it is after the update.
  856. * @since 3.0
  857. * @see Update
  858. * @see AggregationUpdate
  859. */
  860. @Nullable
  861. <T> T findAndModify(Query query, UpdateDefinition update, FindAndModifyOptions options, Class<T> entityClass);
  862. /**
  863. * Triggers <a href="https://docs.mongodb.org/manual/reference/method/db.collection.findAndModify/">findAndModify </a>
  864. * to apply provided {@link Update} on documents matching {@link Criteria} of given {@link Query} taking
  865. * {@link FindAndModifyOptions} into account.
  866. *
  867. * @param query the {@link Query} class that specifies the {@link Criteria} used to find a record and also an optional
  868. * fields specification. Must not be {@literal null}.
  869. * @param update the {@link UpdateDefinition} to apply on matching documents. Must not be {@literal null}.
  870. * @param options the {@link FindAndModifyOptions} holding additional information. Must not be {@literal null}.
  871. * @param entityClass the parametrized type. Must not be {@literal null}.
  872. * @param collectionName the collection to query. Must not be {@literal null}.
  873. * @return the converted object that was updated or {@literal null}, if not found. Depending on the value of
  874. * {@link FindAndModifyOptions#isReturnNew()} this will either be the object as it was before the update or as
  875. * it is after the update.
  876. * @since 3.0
  877. * @see Update
  878. * @see AggregationUpdate
  879. */
  880. @Nullable
  881. <T> T findAndModify(Query query, UpdateDefinition update, FindAndModifyOptions options, Class<T> entityClass,
  882. String collectionName);
  883. /**
  884. * Triggers
  885. * <a href="https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndReplace/">findOneAndReplace</a>
  886. * to replace a single document matching {@link Criteria} of given {@link Query} with the {@code replacement}
  887. * document. <br />
  888. * The collection name is derived from the {@literal replacement} type. <br />
  889. * Options are defaulted to {@link FindAndReplaceOptions#empty()}. <br />
  890. * <strong>NOTE:</strong> The replacement entity must not hold an {@literal id}.
  891. *
  892. * @param query the {@link Query} class that specifies the {@link Criteria} used to find a record and also an optional
  893. * fields specification. Must not be {@literal null}.
  894. * @param replacement the replacement document. Must not be {@literal null}.
  895. * @return the converted object that was updated or {@literal null}, if not found.
  896. * @since 2.1
  897. */
  898. @Nullable
  899. default <T> T findAndReplace(Query query, T replacement) {
  900. return findAndReplace(query, replacement, FindAndReplaceOptions.empty());
  901. }
  902. /**
  903. * Triggers
  904. * <a href="https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndReplace/">findOneAndReplace</a>
  905. * to replace a single document matching {@link Criteria} of given {@link Query} with the {@code replacement}
  906. * document.<br />
  907. * Options are defaulted to {@link FindAndReplaceOptions#empty()}. <br />
  908. * <strong>NOTE:</strong> The replacement entity must not hold an {@literal id}.
  909. *
  910. * @param query the {@link Query} class that specifies the {@link Criteria} used to find a record and also an optional
  911. * fields specification. Must not be {@literal null}.
  912. * @param replacement the replacement document. Must not be {@literal null}.
  913. * @param collectionName the collection to query. Must not be {@literal null}.
  914. * @return the converted object that was updated or {@literal null}, if not found.
  915. * @since 2.1
  916. */
  917. @Nullable
  918. default <T> T findAndReplace(Query query, T replacement, String collectionName) {
  919. return findAndReplace(query, replacement, FindAndReplaceOptions.empty(), collectionName);
  920. }
  921. /**
  922. * Triggers
  923. * <a href="https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndReplace/">findOneAndReplace</a>
  924. * to replace a single document matching {@link Criteria} of given {@link Query} with the {@code replacement} document
  925. * taking {@link FindAndReplaceOptions} into account.<br />
  926. * <strong>NOTE:</strong> The replacement entity must not hold an {@literal id}.
  927. *
  928. * @param query the {@link Query} class that specifies the {@link Criteria} used to find a record and also an optional
  929. * fields specification. Must not be {@literal null}.
  930. * @param replacement the replacement document. Must not be {@literal null}.
  931. * @param options the {@link FindAndModifyOptions} holding additional information. Must not be {@literal null}.
  932. * @return the converted object that was updated or {@literal null}, if not found. Depending on the value of
  933. * {@link FindAndReplaceOptions#isReturnNew()} this will either be the object as it was before the update or
  934. * as it is after the update.
  935. * @since 2.1
  936. */
  937. @Nullable
  938. default <T> T findAndReplace(Query query, T replacement, FindAndReplaceOptions options) {
  939. return findAndReplace(query, replacement, options, getCollectionName(ClassUtils.getUserClass(replacement)));
  940. }
  941. /**
  942. * Triggers
  943. * <a href="https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndReplace/">findOneAndReplace</a>
  944. * to replace a single document matching {@link Criteria} of given {@link Query} with the {@code replacement} document
  945. * taking {@link FindAndReplaceOptions} into account.<br />
  946. * <strong>NOTE:</strong> The replacement entity must not hold an {@literal id}.
  947. *
  948. * @param query the {@link Query} class that specifies theā€¦

Large files files are truncated, but you can click here to view the full file