collection.js 27 KB

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