collection.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.Collection = void 0;
  4. const bson_1 = require("./bson");
  5. const ordered_1 = require("./bulk/ordered");
  6. const unordered_1 = require("./bulk/unordered");
  7. const change_stream_1 = require("./change_stream");
  8. const aggregation_cursor_1 = require("./cursor/aggregation_cursor");
  9. const find_cursor_1 = require("./cursor/find_cursor");
  10. const list_indexes_cursor_1 = require("./cursor/list_indexes_cursor");
  11. const list_search_indexes_cursor_1 = require("./cursor/list_search_indexes_cursor");
  12. const error_1 = require("./error");
  13. const bulk_write_1 = require("./operations/bulk_write");
  14. const count_1 = require("./operations/count");
  15. const count_documents_1 = require("./operations/count_documents");
  16. const delete_1 = require("./operations/delete");
  17. const distinct_1 = require("./operations/distinct");
  18. const drop_1 = require("./operations/drop");
  19. const estimated_document_count_1 = require("./operations/estimated_document_count");
  20. const execute_operation_1 = require("./operations/execute_operation");
  21. const find_and_modify_1 = require("./operations/find_and_modify");
  22. const indexes_1 = require("./operations/indexes");
  23. const insert_1 = require("./operations/insert");
  24. const is_capped_1 = require("./operations/is_capped");
  25. const options_operation_1 = require("./operations/options_operation");
  26. const rename_1 = require("./operations/rename");
  27. const create_1 = require("./operations/search_indexes/create");
  28. const drop_2 = require("./operations/search_indexes/drop");
  29. const update_1 = require("./operations/search_indexes/update");
  30. const stats_1 = require("./operations/stats");
  31. const update_2 = require("./operations/update");
  32. const read_concern_1 = require("./read_concern");
  33. const read_preference_1 = require("./read_preference");
  34. const utils_1 = require("./utils");
  35. const write_concern_1 = require("./write_concern");
  36. /**
  37. * The **Collection** class is an internal class that embodies a MongoDB collection
  38. * allowing for insert/find/update/delete and other command operation on that MongoDB collection.
  39. *
  40. * **COLLECTION Cannot directly be instantiated**
  41. * @public
  42. *
  43. * @example
  44. * ```ts
  45. * import { MongoClient } from 'mongodb';
  46. *
  47. * interface Pet {
  48. * name: string;
  49. * kind: 'dog' | 'cat' | 'fish';
  50. * }
  51. *
  52. * const client = new MongoClient('mongodb://localhost:27017');
  53. * const pets = client.db().collection<Pet>('pets');
  54. *
  55. * const petCursor = pets.find();
  56. *
  57. * for await (const pet of petCursor) {
  58. * console.log(`${pet.name} is a ${pet.kind}!`);
  59. * }
  60. * ```
  61. */
  62. class Collection {
  63. /**
  64. * Create a new Collection instance
  65. * @internal
  66. */
  67. constructor(db, name, options) {
  68. (0, utils_1.checkCollectionName)(name);
  69. // Internal state
  70. this.s = {
  71. db,
  72. options,
  73. namespace: new utils_1.MongoDBCollectionNamespace(db.databaseName, name),
  74. pkFactory: db.options?.pkFactory ?? utils_1.DEFAULT_PK_FACTORY,
  75. readPreference: read_preference_1.ReadPreference.fromOptions(options),
  76. bsonOptions: (0, bson_1.resolveBSONOptions)(options, db),
  77. readConcern: read_concern_1.ReadConcern.fromOptions(options),
  78. writeConcern: write_concern_1.WriteConcern.fromOptions(options)
  79. };
  80. this.client = db.client;
  81. }
  82. /**
  83. * The name of the database this collection belongs to
  84. */
  85. get dbName() {
  86. return this.s.namespace.db;
  87. }
  88. /**
  89. * The name of this collection
  90. */
  91. get collectionName() {
  92. return this.s.namespace.collection;
  93. }
  94. /**
  95. * The namespace of this collection, in the format `${this.dbName}.${this.collectionName}`
  96. */
  97. get namespace() {
  98. return this.fullNamespace.toString();
  99. }
  100. /**
  101. * @internal
  102. *
  103. * The `MongoDBNamespace` for the collection.
  104. */
  105. get fullNamespace() {
  106. return this.s.namespace;
  107. }
  108. /**
  109. * The current readConcern of the collection. If not explicitly defined for
  110. * this collection, will be inherited from the parent DB
  111. */
  112. get readConcern() {
  113. if (this.s.readConcern == null) {
  114. return this.s.db.readConcern;
  115. }
  116. return this.s.readConcern;
  117. }
  118. /**
  119. * The current readPreference of the collection. If not explicitly defined for
  120. * this collection, will be inherited from the parent DB
  121. */
  122. get readPreference() {
  123. if (this.s.readPreference == null) {
  124. return this.s.db.readPreference;
  125. }
  126. return this.s.readPreference;
  127. }
  128. get bsonOptions() {
  129. return this.s.bsonOptions;
  130. }
  131. /**
  132. * The current writeConcern of the collection. If not explicitly defined for
  133. * this collection, will be inherited from the parent DB
  134. */
  135. get writeConcern() {
  136. if (this.s.writeConcern == null) {
  137. return this.s.db.writeConcern;
  138. }
  139. return this.s.writeConcern;
  140. }
  141. /** The current index hint for the collection */
  142. get hint() {
  143. return this.s.collectionHint;
  144. }
  145. set hint(v) {
  146. this.s.collectionHint = (0, utils_1.normalizeHintField)(v);
  147. }
  148. /**
  149. * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field,
  150. * one will be added to each of the documents missing it by the driver, mutating the document. This behavior
  151. * can be overridden by setting the **forceServerObjectId** flag.
  152. *
  153. * @param doc - The document to insert
  154. * @param options - Optional settings for the command
  155. */
  156. async insertOne(doc, options) {
  157. return (0, execute_operation_1.executeOperation)(this.client, new insert_1.InsertOneOperation(this, doc, (0, utils_1.resolveOptions)(this, options)));
  158. }
  159. /**
  160. * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field,
  161. * one will be added to each of the documents missing it by the driver, mutating the document. This behavior
  162. * can be overridden by setting the **forceServerObjectId** flag.
  163. *
  164. * @param docs - The documents to insert
  165. * @param options - Optional settings for the command
  166. */
  167. async insertMany(docs, options) {
  168. return (0, execute_operation_1.executeOperation)(this.client, new insert_1.InsertManyOperation(this, docs, (0, utils_1.resolveOptions)(this, options ?? { ordered: true })));
  169. }
  170. /**
  171. * Perform a bulkWrite operation without a fluent API
  172. *
  173. * Legal operation types are
  174. * - `insertOne`
  175. * - `replaceOne`
  176. * - `updateOne`
  177. * - `updateMany`
  178. * - `deleteOne`
  179. * - `deleteMany`
  180. *
  181. * If documents passed in do not contain the **_id** field,
  182. * one will be added to each of the documents missing it by the driver, mutating the document. This behavior
  183. * can be overridden by setting the **forceServerObjectId** flag.
  184. *
  185. * @param operations - Bulk operations to perform
  186. * @param options - Optional settings for the command
  187. * @throws MongoDriverError if operations is not an array
  188. */
  189. async bulkWrite(operations, options) {
  190. if (!Array.isArray(operations)) {
  191. throw new error_1.MongoInvalidArgumentError('Argument "operations" must be an array of documents');
  192. }
  193. return (0, execute_operation_1.executeOperation)(this.client, new bulk_write_1.BulkWriteOperation(this, operations, (0, utils_1.resolveOptions)(this, options ?? { ordered: true })));
  194. }
  195. /**
  196. * Update a single document in a collection
  197. *
  198. * @param filter - The filter used to select the document to update
  199. * @param update - The update operations to be applied to the document
  200. * @param options - Optional settings for the command
  201. */
  202. async updateOne(filter, update, options) {
  203. return (0, execute_operation_1.executeOperation)(this.client, new update_2.UpdateOneOperation(this, filter, update, (0, utils_1.resolveOptions)(this, options)));
  204. }
  205. /**
  206. * Replace a document in a collection with another document
  207. *
  208. * @param filter - The filter used to select the document to replace
  209. * @param replacement - The Document that replaces the matching document
  210. * @param options - Optional settings for the command
  211. */
  212. async replaceOne(filter, replacement, options) {
  213. return (0, execute_operation_1.executeOperation)(this.client, new update_2.ReplaceOneOperation(this, filter, replacement, (0, utils_1.resolveOptions)(this, options)));
  214. }
  215. /**
  216. * Update multiple documents in a collection
  217. *
  218. * @param filter - The filter used to select the documents to update
  219. * @param update - The update operations to be applied to the documents
  220. * @param options - Optional settings for the command
  221. */
  222. async updateMany(filter, update, options) {
  223. return (0, execute_operation_1.executeOperation)(this.client, new update_2.UpdateManyOperation(this, filter, update, (0, utils_1.resolveOptions)(this, options)));
  224. }
  225. /**
  226. * Delete a document from a collection
  227. *
  228. * @param filter - The filter used to select the document to remove
  229. * @param options - Optional settings for the command
  230. */
  231. async deleteOne(filter = {}, options = {}) {
  232. return (0, execute_operation_1.executeOperation)(this.client, new delete_1.DeleteOneOperation(this, filter, (0, utils_1.resolveOptions)(this, options)));
  233. }
  234. /**
  235. * Delete multiple documents from a collection
  236. *
  237. * @param filter - The filter used to select the documents to remove
  238. * @param options - Optional settings for the command
  239. */
  240. async deleteMany(filter = {}, options = {}) {
  241. return (0, execute_operation_1.executeOperation)(this.client, new delete_1.DeleteManyOperation(this, filter, (0, utils_1.resolveOptions)(this, options)));
  242. }
  243. /**
  244. * Rename the collection.
  245. *
  246. * @remarks
  247. * This operation does not inherit options from the Db or MongoClient.
  248. *
  249. * @param newName - New name of of the collection.
  250. * @param options - Optional settings for the command
  251. */
  252. async rename(newName, options) {
  253. // Intentionally, we do not inherit options from parent for this operation.
  254. return (0, execute_operation_1.executeOperation)(this.client, new rename_1.RenameOperation(this, newName, {
  255. ...options,
  256. readPreference: read_preference_1.ReadPreference.PRIMARY
  257. }));
  258. }
  259. /**
  260. * Drop the collection from the database, removing it permanently. New accesses will create a new collection.
  261. *
  262. * @param options - Optional settings for the command
  263. */
  264. async drop(options) {
  265. return (0, execute_operation_1.executeOperation)(this.client, new drop_1.DropCollectionOperation(this.s.db, this.collectionName, options));
  266. }
  267. async findOne(filter = {}, options = {}) {
  268. return this.find(filter, options).limit(-1).batchSize(1).next();
  269. }
  270. find(filter = {}, options = {}) {
  271. return new find_cursor_1.FindCursor(this.client, this.s.namespace, filter, (0, utils_1.resolveOptions)(this, options));
  272. }
  273. /**
  274. * Returns the options of the collection.
  275. *
  276. * @param options - Optional settings for the command
  277. */
  278. async options(options) {
  279. return (0, execute_operation_1.executeOperation)(this.client, new options_operation_1.OptionsOperation(this, (0, utils_1.resolveOptions)(this, options)));
  280. }
  281. /**
  282. * Returns if the collection is a capped collection
  283. *
  284. * @param options - Optional settings for the command
  285. */
  286. async isCapped(options) {
  287. return (0, execute_operation_1.executeOperation)(this.client, new is_capped_1.IsCappedOperation(this, (0, utils_1.resolveOptions)(this, options)));
  288. }
  289. /**
  290. * Creates an index on the db and collection collection.
  291. *
  292. * @param indexSpec - The field name or index specification to create an index for
  293. * @param options - Optional settings for the command
  294. *
  295. * @example
  296. * ```ts
  297. * const collection = client.db('foo').collection('bar');
  298. *
  299. * await collection.createIndex({ a: 1, b: -1 });
  300. *
  301. * // Alternate syntax for { c: 1, d: -1 } that ensures order of indexes
  302. * await collection.createIndex([ [c, 1], [d, -1] ]);
  303. *
  304. * // Equivalent to { e: 1 }
  305. * await collection.createIndex('e');
  306. *
  307. * // Equivalent to { f: 1, g: 1 }
  308. * await collection.createIndex(['f', 'g'])
  309. *
  310. * // Equivalent to { h: 1, i: -1 }
  311. * await collection.createIndex([ { h: 1 }, { i: -1 } ]);
  312. *
  313. * // Equivalent to { j: 1, k: -1, l: 2d }
  314. * await collection.createIndex(['j', ['k', -1], { l: '2d' }])
  315. * ```
  316. */
  317. async createIndex(indexSpec, options) {
  318. return (0, execute_operation_1.executeOperation)(this.client, new indexes_1.CreateIndexOperation(this, this.collectionName, indexSpec, (0, utils_1.resolveOptions)(this, options)));
  319. }
  320. /**
  321. * Creates multiple indexes in the collection, this method is only supported for
  322. * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported
  323. * error.
  324. *
  325. * **Note**: Unlike {@link Collection#createIndex| createIndex}, this function takes in raw index specifications.
  326. * Index specifications are defined {@link https://www.mongodb.com/docs/manual/reference/command/createIndexes/| here}.
  327. *
  328. * @param indexSpecs - An array of index specifications to be created
  329. * @param options - Optional settings for the command
  330. *
  331. * @example
  332. * ```ts
  333. * const collection = client.db('foo').collection('bar');
  334. * await collection.createIndexes([
  335. * // Simple index on field fizz
  336. * {
  337. * key: { fizz: 1 },
  338. * }
  339. * // wildcard index
  340. * {
  341. * key: { '$**': 1 }
  342. * },
  343. * // named index on darmok and jalad
  344. * {
  345. * key: { darmok: 1, jalad: -1 }
  346. * name: 'tanagra'
  347. * }
  348. * ]);
  349. * ```
  350. */
  351. async createIndexes(indexSpecs, options) {
  352. return (0, execute_operation_1.executeOperation)(this.client, new indexes_1.CreateIndexesOperation(this, this.collectionName, indexSpecs, (0, utils_1.resolveOptions)(this, { ...options, maxTimeMS: undefined })));
  353. }
  354. /**
  355. * Drops an index from this collection.
  356. *
  357. * @param indexName - Name of the index to drop.
  358. * @param options - Optional settings for the command
  359. */
  360. async dropIndex(indexName, options) {
  361. return (0, execute_operation_1.executeOperation)(this.client, new indexes_1.DropIndexOperation(this, indexName, {
  362. ...(0, utils_1.resolveOptions)(this, options),
  363. readPreference: read_preference_1.ReadPreference.primary
  364. }));
  365. }
  366. /**
  367. * Drops all indexes from this collection.
  368. *
  369. * @param options - Optional settings for the command
  370. */
  371. async dropIndexes(options) {
  372. return (0, execute_operation_1.executeOperation)(this.client, new indexes_1.DropIndexesOperation(this, (0, utils_1.resolveOptions)(this, options)));
  373. }
  374. /**
  375. * Get the list of all indexes information for the collection.
  376. *
  377. * @param options - Optional settings for the command
  378. */
  379. listIndexes(options) {
  380. return new list_indexes_cursor_1.ListIndexesCursor(this, (0, utils_1.resolveOptions)(this, options));
  381. }
  382. /**
  383. * Checks if one or more indexes exist on the collection, fails on first non-existing index
  384. *
  385. * @param indexes - One or more index names to check.
  386. * @param options - Optional settings for the command
  387. */
  388. async indexExists(indexes, options) {
  389. return (0, execute_operation_1.executeOperation)(this.client, new indexes_1.IndexExistsOperation(this, indexes, (0, utils_1.resolveOptions)(this, options)));
  390. }
  391. /**
  392. * Retrieves this collections index info.
  393. *
  394. * @param options - Optional settings for the command
  395. */
  396. async indexInformation(options) {
  397. return (0, execute_operation_1.executeOperation)(this.client, new indexes_1.IndexInformationOperation(this.s.db, this.collectionName, (0, utils_1.resolveOptions)(this, options)));
  398. }
  399. /**
  400. * Gets an estimate of the count of documents in a collection using collection metadata.
  401. * This will always run a count command on all server versions.
  402. *
  403. * due to an oversight in versions 5.0.0-5.0.8 of MongoDB, the count command,
  404. * which estimatedDocumentCount uses in its implementation, was not included in v1 of
  405. * the Stable API, and so users of the Stable API with estimatedDocumentCount are
  406. * recommended to upgrade their server version to 5.0.9+ or set apiStrict: false to avoid
  407. * encountering errors.
  408. *
  409. * @see {@link https://www.mongodb.com/docs/manual/reference/command/count/#behavior|Count: Behavior}
  410. * @param options - Optional settings for the command
  411. */
  412. async estimatedDocumentCount(options) {
  413. return (0, execute_operation_1.executeOperation)(this.client, new estimated_document_count_1.EstimatedDocumentCountOperation(this, (0, utils_1.resolveOptions)(this, options)));
  414. }
  415. /**
  416. * Gets the number of documents matching the filter.
  417. * For a fast count of the total documents in a collection see {@link Collection#estimatedDocumentCount| estimatedDocumentCount}.
  418. * **Note**: When migrating from {@link Collection#count| count} to {@link Collection#countDocuments| countDocuments}
  419. * the following query operators must be replaced:
  420. *
  421. * | Operator | Replacement |
  422. * | -------- | ----------- |
  423. * | `$where` | [`$expr`][1] |
  424. * | `$near` | [`$geoWithin`][2] with [`$center`][3] |
  425. * | `$nearSphere` | [`$geoWithin`][2] with [`$centerSphere`][4] |
  426. *
  427. * [1]: https://www.mongodb.com/docs/manual/reference/operator/query/expr/
  428. * [2]: https://www.mongodb.com/docs/manual/reference/operator/query/geoWithin/
  429. * [3]: https://www.mongodb.com/docs/manual/reference/operator/query/center/#op._S_center
  430. * [4]: https://www.mongodb.com/docs/manual/reference/operator/query/centerSphere/#op._S_centerSphere
  431. *
  432. * @param filter - The filter for the count
  433. * @param options - Optional settings for the command
  434. *
  435. * @see https://www.mongodb.com/docs/manual/reference/operator/query/expr/
  436. * @see https://www.mongodb.com/docs/manual/reference/operator/query/geoWithin/
  437. * @see https://www.mongodb.com/docs/manual/reference/operator/query/center/#op._S_center
  438. * @see https://www.mongodb.com/docs/manual/reference/operator/query/centerSphere/#op._S_centerSphere
  439. */
  440. async countDocuments(filter = {}, options = {}) {
  441. return (0, execute_operation_1.executeOperation)(this.client, new count_documents_1.CountDocumentsOperation(this, filter, (0, utils_1.resolveOptions)(this, options)));
  442. }
  443. async distinct(key, filter = {}, options = {}) {
  444. return (0, execute_operation_1.executeOperation)(this.client, new distinct_1.DistinctOperation(this, key, filter, (0, utils_1.resolveOptions)(this, options)));
  445. }
  446. /**
  447. * Retrieve all the indexes on the collection.
  448. *
  449. * @param options - Optional settings for the command
  450. */
  451. async indexes(options) {
  452. return (0, execute_operation_1.executeOperation)(this.client, new indexes_1.IndexesOperation(this, (0, utils_1.resolveOptions)(this, options)));
  453. }
  454. /**
  455. * Get all the collection statistics.
  456. *
  457. * @deprecated the `collStats` operation will be removed in the next major release. Please
  458. * use an aggregation pipeline with the [`$collStats`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collStats/) stage instead
  459. *
  460. * @param options - Optional settings for the command
  461. */
  462. async stats(options) {
  463. return (0, execute_operation_1.executeOperation)(this.client, new stats_1.CollStatsOperation(this, options));
  464. }
  465. async findOneAndDelete(filter, options) {
  466. return (0, execute_operation_1.executeOperation)(this.client, new find_and_modify_1.FindOneAndDeleteOperation(this, filter, (0, utils_1.resolveOptions)(this, options)));
  467. }
  468. async findOneAndReplace(filter, replacement, options) {
  469. return (0, execute_operation_1.executeOperation)(this.client, new find_and_modify_1.FindOneAndReplaceOperation(this, filter, replacement, (0, utils_1.resolveOptions)(this, options)));
  470. }
  471. async findOneAndUpdate(filter, update, options) {
  472. return (0, execute_operation_1.executeOperation)(this.client, new find_and_modify_1.FindOneAndUpdateOperation(this, filter, update, (0, utils_1.resolveOptions)(this, options)));
  473. }
  474. /**
  475. * Execute an aggregation framework pipeline against the collection, needs MongoDB \>= 2.2
  476. *
  477. * @param pipeline - An array of aggregation pipelines to execute
  478. * @param options - Optional settings for the command
  479. */
  480. aggregate(pipeline = [], options) {
  481. if (!Array.isArray(pipeline)) {
  482. throw new error_1.MongoInvalidArgumentError('Argument "pipeline" must be an array of aggregation stages');
  483. }
  484. return new aggregation_cursor_1.AggregationCursor(this.client, this.s.namespace, pipeline, (0, utils_1.resolveOptions)(this, options));
  485. }
  486. /**
  487. * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection.
  488. *
  489. * @remarks
  490. * watch() accepts two generic arguments for distinct use cases:
  491. * - The first is to override the schema that may be defined for this specific collection
  492. * - The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument
  493. * @example
  494. * By just providing the first argument I can type the change to be `ChangeStreamDocument<{ _id: number }>`
  495. * ```ts
  496. * collection.watch<{ _id: number }>()
  497. * .on('change', change => console.log(change._id.toFixed(4)));
  498. * ```
  499. *
  500. * @example
  501. * Passing a second argument provides a way to reflect the type changes caused by an advanced pipeline.
  502. * Here, we are using a pipeline to have MongoDB filter for insert changes only and add a comment.
  503. * No need start from scratch on the ChangeStreamInsertDocument type!
  504. * By using an intersection we can save time and ensure defaults remain the same type!
  505. * ```ts
  506. * collection
  507. * .watch<Schema, ChangeStreamInsertDocument<Schema> & { comment: string }>([
  508. * { $addFields: { comment: 'big changes' } },
  509. * { $match: { operationType: 'insert' } }
  510. * ])
  511. * .on('change', change => {
  512. * change.comment.startsWith('big');
  513. * change.operationType === 'insert';
  514. * // No need to narrow in code because the generics did that for us!
  515. * expectType<Schema>(change.fullDocument);
  516. * });
  517. * ```
  518. *
  519. * @param pipeline - An array of {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents.
  520. * @param options - Optional settings for the command
  521. * @typeParam TLocal - Type of the data being detected by the change stream
  522. * @typeParam TChange - Type of the whole change stream document emitted
  523. */
  524. watch(pipeline = [], options = {}) {
  525. // Allow optionally not specifying a pipeline
  526. if (!Array.isArray(pipeline)) {
  527. options = pipeline;
  528. pipeline = [];
  529. }
  530. return new change_stream_1.ChangeStream(this, pipeline, (0, utils_1.resolveOptions)(this, options));
  531. }
  532. /**
  533. * Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order.
  534. *
  535. * @throws MongoNotConnectedError
  536. * @remarks
  537. * **NOTE:** MongoClient must be connected prior to calling this method due to a known limitation in this legacy implementation.
  538. * However, `collection.bulkWrite()` provides an equivalent API that does not require prior connecting.
  539. */
  540. initializeUnorderedBulkOp(options) {
  541. return new unordered_1.UnorderedBulkOperation(this, (0, utils_1.resolveOptions)(this, options));
  542. }
  543. /**
  544. * Initiate an In order bulk write operation. Operations will be serially executed in the order they are added, creating a new operation for each switch in types.
  545. *
  546. * @throws MongoNotConnectedError
  547. * @remarks
  548. * **NOTE:** MongoClient must be connected prior to calling this method due to a known limitation in this legacy implementation.
  549. * However, `collection.bulkWrite()` provides an equivalent API that does not require prior connecting.
  550. */
  551. initializeOrderedBulkOp(options) {
  552. return new ordered_1.OrderedBulkOperation(this, (0, utils_1.resolveOptions)(this, options));
  553. }
  554. /**
  555. * An estimated count of matching documents in the db to a filter.
  556. *
  557. * **NOTE:** This method has been deprecated, since it does not provide an accurate count of the documents
  558. * in a collection. To obtain an accurate count of documents in the collection, use {@link Collection#countDocuments| countDocuments}.
  559. * To obtain an estimated count of all documents in the collection, use {@link Collection#estimatedDocumentCount| estimatedDocumentCount}.
  560. *
  561. * @deprecated use {@link Collection#countDocuments| countDocuments} or {@link Collection#estimatedDocumentCount| estimatedDocumentCount} instead
  562. *
  563. * @param filter - The filter for the count.
  564. * @param options - Optional settings for the command
  565. */
  566. async count(filter = {}, options = {}) {
  567. return (0, execute_operation_1.executeOperation)(this.client, new count_1.CountOperation(this.fullNamespace, filter, (0, utils_1.resolveOptions)(this, options)));
  568. }
  569. listSearchIndexes(indexNameOrOptions, options) {
  570. options =
  571. typeof indexNameOrOptions === 'object' ? indexNameOrOptions : options == null ? {} : options;
  572. const indexName = indexNameOrOptions == null
  573. ? null
  574. : typeof indexNameOrOptions === 'object'
  575. ? null
  576. : indexNameOrOptions;
  577. return new list_search_indexes_cursor_1.ListSearchIndexesCursor(this, indexName, options);
  578. }
  579. /**
  580. * Creates a single search index for the collection.
  581. *
  582. * @param description - The index description for the new search index.
  583. * @returns A promise that resolves to the name of the new search index.
  584. *
  585. * @remarks Only available when used against a 7.0+ Atlas cluster.
  586. */
  587. async createSearchIndex(description) {
  588. const [index] = await this.createSearchIndexes([description]);
  589. return index;
  590. }
  591. /**
  592. * Creates multiple search indexes for the current collection.
  593. *
  594. * @param descriptions - An array of `SearchIndexDescription`s for the new search indexes.
  595. * @returns A promise that resolves to an array of the newly created search index names.
  596. *
  597. * @remarks Only available when used against a 7.0+ Atlas cluster.
  598. * @returns
  599. */
  600. async createSearchIndexes(descriptions) {
  601. return (0, execute_operation_1.executeOperation)(this.client, new create_1.CreateSearchIndexesOperation(this, descriptions));
  602. }
  603. /**
  604. * Deletes a search index by index name.
  605. *
  606. * @param name - The name of the search index to be deleted.
  607. *
  608. * @remarks Only available when used against a 7.0+ Atlas cluster.
  609. */
  610. async dropSearchIndex(name) {
  611. return (0, execute_operation_1.executeOperation)(this.client, new drop_2.DropSearchIndexOperation(this, name));
  612. }
  613. /**
  614. * Updates a search index by replacing the existing index definition with the provided definition.
  615. *
  616. * @param name - The name of the search index to update.
  617. * @param definition - The new search index definition.
  618. *
  619. * @remarks Only available when used against a 7.0+ Atlas cluster.
  620. */
  621. async updateSearchIndex(name, definition) {
  622. return (0, execute_operation_1.executeOperation)(this.client, new update_1.UpdateSearchIndexOperation(this, name, definition));
  623. }
  624. }
  625. exports.Collection = Collection;
  626. //# sourceMappingURL=collection.js.map