collection.js 111 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240
  1. 'use strict';
  2. const deprecate = require('util').deprecate;
  3. const deprecateOptions = require('./utils').deprecateOptions;
  4. const emitWarningOnce = require('./utils').emitWarningOnce;
  5. const checkCollectionName = require('./utils').checkCollectionName;
  6. const ObjectID = require('./core').BSON.ObjectID;
  7. const MongoError = require('./core').MongoError;
  8. const normalizeHintField = require('./utils').normalizeHintField;
  9. const decorateCommand = require('./utils').decorateCommand;
  10. const decorateWithCollation = require('./utils').decorateWithCollation;
  11. const decorateWithReadConcern = require('./utils').decorateWithReadConcern;
  12. const formattedOrderClause = require('./utils').formattedOrderClause;
  13. const ReadPreference = require('./core').ReadPreference;
  14. const unordered = require('./bulk/unordered');
  15. const ordered = require('./bulk/ordered');
  16. const ChangeStream = require('./change_stream');
  17. const executeLegacyOperation = require('./utils').executeLegacyOperation;
  18. const WriteConcern = require('./write_concern');
  19. const ReadConcern = require('./read_concern');
  20. const MongoDBNamespace = require('./utils').MongoDBNamespace;
  21. const AggregationCursor = require('./aggregation_cursor');
  22. const CommandCursor = require('./command_cursor');
  23. // Operations
  24. const ensureIndex = require('./operations/collection_ops').ensureIndex;
  25. const group = require('./operations/collection_ops').group;
  26. const parallelCollectionScan = require('./operations/collection_ops').parallelCollectionScan;
  27. const removeDocuments = require('./operations/common_functions').removeDocuments;
  28. const save = require('./operations/collection_ops').save;
  29. const updateDocuments = require('./operations/common_functions').updateDocuments;
  30. const AggregateOperation = require('./operations/aggregate');
  31. const BulkWriteOperation = require('./operations/bulk_write');
  32. const CountDocumentsOperation = require('./operations/count_documents');
  33. const CreateIndexesOperation = require('./operations/create_indexes');
  34. const DeleteManyOperation = require('./operations/delete_many');
  35. const DeleteOneOperation = require('./operations/delete_one');
  36. const DistinctOperation = require('./operations/distinct');
  37. const DropCollectionOperation = require('./operations/drop').DropCollectionOperation;
  38. const DropIndexOperation = require('./operations/drop_index');
  39. const DropIndexesOperation = require('./operations/drop_indexes');
  40. const EstimatedDocumentCountOperation = require('./operations/estimated_document_count');
  41. const FindOperation = require('./operations/find');
  42. const FindOneOperation = require('./operations/find_one');
  43. const FindAndModifyOperation = require('./operations/find_and_modify');
  44. const FindOneAndDeleteOperation = require('./operations/find_one_and_delete');
  45. const FindOneAndReplaceOperation = require('./operations/find_one_and_replace');
  46. const FindOneAndUpdateOperation = require('./operations/find_one_and_update');
  47. const GeoHaystackSearchOperation = require('./operations/geo_haystack_search');
  48. const IndexesOperation = require('./operations/indexes');
  49. const IndexExistsOperation = require('./operations/index_exists');
  50. const IndexInformationOperation = require('./operations/index_information');
  51. const InsertManyOperation = require('./operations/insert_many');
  52. const InsertOneOperation = require('./operations/insert_one');
  53. const IsCappedOperation = require('./operations/is_capped');
  54. const ListIndexesOperation = require('./operations/list_indexes');
  55. const MapReduceOperation = require('./operations/map_reduce');
  56. const OptionsOperation = require('./operations/options_operation');
  57. const RenameOperation = require('./operations/rename');
  58. const ReIndexOperation = require('./operations/re_index');
  59. const ReplaceOneOperation = require('./operations/replace_one');
  60. const StatsOperation = require('./operations/stats');
  61. const UpdateManyOperation = require('./operations/update_many');
  62. const UpdateOneOperation = require('./operations/update_one');
  63. const executeOperation = require('./operations/execute_operation');
  64. /**
  65. * @fileOverview The **Collection** class is an internal class that embodies a MongoDB collection
  66. * allowing for insert/update/remove/find and other command operation on that MongoDB collection.
  67. *
  68. * **COLLECTION Cannot directly be instantiated**
  69. * @example
  70. * const MongoClient = require('mongodb').MongoClient;
  71. * const test = require('assert');
  72. * // Connection url
  73. * const url = 'mongodb://localhost:27017';
  74. * // Database Name
  75. * const dbName = 'test';
  76. * // Connect using MongoClient
  77. * MongoClient.connect(url, function(err, client) {
  78. * // Create a collection we want to drop later
  79. * const col = client.db(dbName).collection('createIndexExample1');
  80. * // Show that duplicate records got dropped
  81. * col.find({}).toArray(function(err, items) {
  82. * test.equal(null, err);
  83. * test.equal(4, items.length);
  84. * client.close();
  85. * });
  86. * });
  87. */
  88. const mergeKeys = ['ignoreUndefined'];
  89. /**
  90. * Create a new Collection instance (INTERNAL TYPE, do not instantiate directly)
  91. * @class
  92. */
  93. function Collection(db, topology, dbName, name, pkFactory, options) {
  94. checkCollectionName(name);
  95. // Unpack variables
  96. const internalHint = null;
  97. const slaveOk = options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk;
  98. const serializeFunctions =
  99. options == null || options.serializeFunctions == null
  100. ? db.s.options.serializeFunctions
  101. : options.serializeFunctions;
  102. const raw = options == null || options.raw == null ? db.s.options.raw : options.raw;
  103. const promoteLongs =
  104. options == null || options.promoteLongs == null
  105. ? db.s.options.promoteLongs
  106. : options.promoteLongs;
  107. const promoteValues =
  108. options == null || options.promoteValues == null
  109. ? db.s.options.promoteValues
  110. : options.promoteValues;
  111. const promoteBuffers =
  112. options == null || options.promoteBuffers == null
  113. ? db.s.options.promoteBuffers
  114. : options.promoteBuffers;
  115. const collectionHint = null;
  116. const namespace = new MongoDBNamespace(dbName, name);
  117. // Get the promiseLibrary
  118. const promiseLibrary = options.promiseLibrary || Promise;
  119. // Set custom primary key factory if provided
  120. pkFactory = pkFactory == null ? ObjectID : pkFactory;
  121. // Internal state
  122. this.s = {
  123. // Set custom primary key factory if provided
  124. pkFactory: pkFactory,
  125. // Db
  126. db: db,
  127. // Topology
  128. topology: topology,
  129. // Options
  130. options: options,
  131. // Namespace
  132. namespace: namespace,
  133. // Read preference
  134. readPreference: ReadPreference.fromOptions(options),
  135. // SlaveOK
  136. slaveOk: slaveOk,
  137. // Serialize functions
  138. serializeFunctions: serializeFunctions,
  139. // Raw
  140. raw: raw,
  141. // promoteLongs
  142. promoteLongs: promoteLongs,
  143. // promoteValues
  144. promoteValues: promoteValues,
  145. // promoteBuffers
  146. promoteBuffers: promoteBuffers,
  147. // internalHint
  148. internalHint: internalHint,
  149. // collectionHint
  150. collectionHint: collectionHint,
  151. // Promise library
  152. promiseLibrary: promiseLibrary,
  153. // Read Concern
  154. readConcern: ReadConcern.fromOptions(options),
  155. // Write Concern
  156. writeConcern: WriteConcern.fromOptions(options)
  157. };
  158. }
  159. /**
  160. * The name of the database this collection belongs to
  161. * @member {string} dbName
  162. * @memberof Collection#
  163. * @readonly
  164. */
  165. Object.defineProperty(Collection.prototype, 'dbName', {
  166. enumerable: true,
  167. get: function() {
  168. return this.s.namespace.db;
  169. }
  170. });
  171. /**
  172. * The name of this collection
  173. * @member {string} collectionName
  174. * @memberof Collection#
  175. * @readonly
  176. */
  177. Object.defineProperty(Collection.prototype, 'collectionName', {
  178. enumerable: true,
  179. get: function() {
  180. return this.s.namespace.collection;
  181. }
  182. });
  183. /**
  184. * The namespace of this collection, in the format `${this.dbName}.${this.collectionName}`
  185. * @member {string} namespace
  186. * @memberof Collection#
  187. * @readonly
  188. */
  189. Object.defineProperty(Collection.prototype, 'namespace', {
  190. enumerable: true,
  191. get: function() {
  192. return this.s.namespace.toString();
  193. }
  194. });
  195. /**
  196. * The current readConcern of the collection. If not explicitly defined for
  197. * this collection, will be inherited from the parent DB
  198. * @member {ReadConcern} [readConcern]
  199. * @memberof Collection#
  200. * @readonly
  201. */
  202. Object.defineProperty(Collection.prototype, 'readConcern', {
  203. enumerable: true,
  204. get: function() {
  205. if (this.s.readConcern == null) {
  206. return this.s.db.readConcern;
  207. }
  208. return this.s.readConcern;
  209. }
  210. });
  211. /**
  212. * The current readPreference of the collection. If not explicitly defined for
  213. * this collection, will be inherited from the parent DB
  214. * @member {ReadPreference} [readPreference]
  215. * @memberof Collection#
  216. * @readonly
  217. */
  218. Object.defineProperty(Collection.prototype, 'readPreference', {
  219. enumerable: true,
  220. get: function() {
  221. if (this.s.readPreference == null) {
  222. return this.s.db.readPreference;
  223. }
  224. return this.s.readPreference;
  225. }
  226. });
  227. /**
  228. * The current writeConcern of the collection. If not explicitly defined for
  229. * this collection, will be inherited from the parent DB
  230. * @member {WriteConcern} [writeConcern]
  231. * @memberof Collection#
  232. * @readonly
  233. */
  234. Object.defineProperty(Collection.prototype, 'writeConcern', {
  235. enumerable: true,
  236. get: function() {
  237. if (this.s.writeConcern == null) {
  238. return this.s.db.writeConcern;
  239. }
  240. return this.s.writeConcern;
  241. }
  242. });
  243. /**
  244. * The current index hint for the collection
  245. * @member {object} [hint]
  246. * @memberof Collection#
  247. */
  248. Object.defineProperty(Collection.prototype, 'hint', {
  249. enumerable: true,
  250. get: function() {
  251. return this.s.collectionHint;
  252. },
  253. set: function(v) {
  254. this.s.collectionHint = normalizeHintField(v);
  255. }
  256. });
  257. const DEPRECATED_FIND_OPTIONS = ['maxScan', 'fields', 'snapshot', 'oplogReplay'];
  258. /**
  259. * Creates a cursor for a query that can be used to iterate over results from MongoDB
  260. * @method
  261. * @param {object} [query={}] The cursor query object.
  262. * @param {object} [options] Optional settings.
  263. * @param {number} [options.limit=0] Sets the limit of documents returned in the query.
  264. * @param {(array|object)} [options.sort] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc.
  265. * @param {object} [options.projection] The fields to return in the query. Object of fields to either include or exclude (one of, not both), {'a':1, 'b': 1} **or** {'a': 0, 'b': 0}
  266. * @param {object} [options.fields] **Deprecated** Use `options.projection` instead
  267. * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination).
  268. * @param {Object} [options.hint] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1}
  269. * @param {boolean} [options.snapshot=false] DEPRECATED: Snapshot query.
  270. * @param {boolean} [options.timeout=false] Specify if the cursor can timeout.
  271. * @param {boolean} [options.tailable=false] Specify if the cursor is tailable.
  272. * @param {boolean} [options.awaitData=false] Specify if the cursor is a a tailable-await cursor. Requires `tailable` to be true
  273. * @param {number} [options.batchSize=1000] Set the batchSize for the getMoreCommand when iterating over the query results.
  274. * @param {boolean} [options.returnKey=false] Only return the index key.
  275. * @param {number} [options.maxScan] DEPRECATED: Limit the number of items to scan.
  276. * @param {number} [options.min] Set index bounds.
  277. * @param {number} [options.max] Set index bounds.
  278. * @param {boolean} [options.showDiskLoc=false] Show disk location of results.
  279. * @param {string} [options.comment] You can put a $comment field on a query to make looking in the profiler logs simpler.
  280. * @param {boolean} [options.raw=false] Return document results as raw BSON buffers.
  281. * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution.
  282. * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types.
  283. * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers.
  284. * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  285. * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system
  286. * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query.
  287. * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. Requires `tailable` and `awaitData` to be true
  288. * @param {boolean} [options.noCursorTimeout] The server normally times out idle cursors after an inactivity period (10 minutes) to prevent excess memory use. Set this option to prevent that.
  289. * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
  290. * @param {boolean} [options.allowDiskUse] Enables writing to temporary files on the server.
  291. * @param {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output.
  292. * @param {ClientSession} [options.session] optional session to use for this operation
  293. * @throws {MongoError}
  294. * @return {Cursor}
  295. */
  296. Collection.prototype.find = deprecateOptions(
  297. {
  298. name: 'collection.find',
  299. deprecatedOptions: DEPRECATED_FIND_OPTIONS,
  300. optionsIndex: 1
  301. },
  302. function(query, options, callback) {
  303. if (typeof callback === 'object') {
  304. // TODO(MAJOR): throw in the future
  305. emitWarningOnce('Third parameter to `find()` must be a callback or undefined');
  306. }
  307. let selector = query;
  308. // figuring out arguments
  309. if (typeof callback !== 'function') {
  310. if (typeof options === 'function') {
  311. callback = options;
  312. options = undefined;
  313. } else if (options == null) {
  314. callback = typeof selector === 'function' ? selector : undefined;
  315. selector = typeof selector === 'object' ? selector : undefined;
  316. }
  317. }
  318. // Ensure selector is not null
  319. selector = selector == null ? {} : selector;
  320. // Validate correctness off the selector
  321. const object = selector;
  322. if (Buffer.isBuffer(object)) {
  323. const object_size = object[0] | (object[1] << 8) | (object[2] << 16) | (object[3] << 24);
  324. if (object_size !== object.length) {
  325. const error = new Error(
  326. 'query selector raw message size does not match message header size [' +
  327. object.length +
  328. '] != [' +
  329. object_size +
  330. ']'
  331. );
  332. error.name = 'MongoError';
  333. throw error;
  334. }
  335. }
  336. // Check special case where we are using an objectId
  337. if (selector != null && selector._bsontype === 'ObjectID') {
  338. selector = { _id: selector };
  339. }
  340. if (!options) options = {};
  341. let projection = options.projection || options.fields;
  342. if (projection && !Buffer.isBuffer(projection) && Array.isArray(projection)) {
  343. projection = projection.length
  344. ? projection.reduce((result, field) => {
  345. result[field] = 1;
  346. return result;
  347. }, {})
  348. : { _id: 1 };
  349. }
  350. // Make a shallow copy of options
  351. let newOptions = Object.assign({}, options);
  352. // Make a shallow copy of the collection options
  353. for (let key in this.s.options) {
  354. if (mergeKeys.indexOf(key) !== -1) {
  355. newOptions[key] = this.s.options[key];
  356. }
  357. }
  358. // Unpack options
  359. newOptions.skip = options.skip ? options.skip : 0;
  360. newOptions.limit = options.limit ? options.limit : 0;
  361. newOptions.raw = typeof options.raw === 'boolean' ? options.raw : this.s.raw;
  362. newOptions.hint =
  363. options.hint != null ? normalizeHintField(options.hint) : this.s.collectionHint;
  364. newOptions.timeout = typeof options.timeout === 'undefined' ? undefined : options.timeout;
  365. // // If we have overridden slaveOk otherwise use the default db setting
  366. newOptions.slaveOk = options.slaveOk != null ? options.slaveOk : this.s.db.slaveOk;
  367. // Add read preference if needed
  368. newOptions.readPreference = ReadPreference.resolve(this, newOptions);
  369. // Set slave ok to true if read preference different from primary
  370. if (
  371. newOptions.readPreference != null &&
  372. (newOptions.readPreference !== 'primary' || newOptions.readPreference.mode !== 'primary')
  373. ) {
  374. newOptions.slaveOk = true;
  375. }
  376. // Ensure the query is an object
  377. if (selector != null && typeof selector !== 'object') {
  378. throw MongoError.create({ message: 'query selector must be an object', driver: true });
  379. }
  380. // Build the find command
  381. const findCommand = {
  382. find: this.s.namespace.toString(),
  383. limit: newOptions.limit,
  384. skip: newOptions.skip,
  385. query: selector
  386. };
  387. if (typeof options.allowDiskUse === 'boolean') {
  388. findCommand.allowDiskUse = options.allowDiskUse;
  389. }
  390. // Ensure we use the right await data option
  391. if (typeof newOptions.awaitdata === 'boolean') {
  392. newOptions.awaitData = newOptions.awaitdata;
  393. }
  394. // Translate to new command option noCursorTimeout
  395. if (typeof newOptions.timeout === 'boolean') newOptions.noCursorTimeout = !newOptions.timeout;
  396. decorateCommand(findCommand, newOptions, ['session', 'collation']);
  397. if (projection) findCommand.fields = projection;
  398. // Add db object to the new options
  399. newOptions.db = this.s.db;
  400. // Add the promise library
  401. newOptions.promiseLibrary = this.s.promiseLibrary;
  402. // Set raw if available at collection level
  403. if (newOptions.raw == null && typeof this.s.raw === 'boolean') newOptions.raw = this.s.raw;
  404. // Set promoteLongs if available at collection level
  405. if (newOptions.promoteLongs == null && typeof this.s.promoteLongs === 'boolean')
  406. newOptions.promoteLongs = this.s.promoteLongs;
  407. if (newOptions.promoteValues == null && typeof this.s.promoteValues === 'boolean')
  408. newOptions.promoteValues = this.s.promoteValues;
  409. if (newOptions.promoteBuffers == null && typeof this.s.promoteBuffers === 'boolean')
  410. newOptions.promoteBuffers = this.s.promoteBuffers;
  411. // Sort options
  412. if (findCommand.sort) {
  413. findCommand.sort = formattedOrderClause(findCommand.sort);
  414. }
  415. // Set the readConcern
  416. decorateWithReadConcern(findCommand, this, options);
  417. // Decorate find command with collation options
  418. try {
  419. decorateWithCollation(findCommand, this, options);
  420. } catch (err) {
  421. if (typeof callback === 'function') return callback(err, null);
  422. throw err;
  423. }
  424. const cursor = this.s.topology.cursor(
  425. new FindOperation(this, this.s.namespace, findCommand, newOptions),
  426. newOptions
  427. );
  428. // TODO: remove this when NODE-2074 is resolved
  429. if (typeof callback === 'function') {
  430. callback(null, cursor);
  431. return;
  432. }
  433. return cursor;
  434. }
  435. );
  436. /**
  437. * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field,
  438. * one will be added to each of the documents missing it by the driver, mutating the document. This behavior
  439. * can be overridden by setting the **forceServerObjectId** flag.
  440. *
  441. * @method
  442. * @param {object} doc Document to insert.
  443. * @param {object} [options] Optional settings.
  444. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  445. * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver.
  446. * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead.
  447. * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead.
  448. * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead.
  449. * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings.
  450. * @param {boolean} [options.checkKeys=true] If true, will throw if bson documents start with `$` or include a `.` in any key value
  451. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
  452. * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
  453. * @param {ClientSession} [options.session] optional session to use for this operation
  454. * @param {Collection~insertOneWriteOpCallback} [callback] The command result callback
  455. * @return {Promise} returns Promise if no callback passed
  456. */
  457. Collection.prototype.insertOne = function(doc, options, callback) {
  458. if (typeof options === 'function') (callback = options), (options = {});
  459. options = options || {};
  460. // Add ignoreUndefined
  461. if (this.s.options.ignoreUndefined) {
  462. options = Object.assign({}, options);
  463. options.ignoreUndefined = this.s.options.ignoreUndefined;
  464. }
  465. const insertOneOperation = new InsertOneOperation(this, doc, options);
  466. return executeOperation(this.s.topology, insertOneOperation, callback);
  467. };
  468. /**
  469. * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field,
  470. * one will be added to each of the documents missing it by the driver, mutating the document. This behavior
  471. * can be overridden by setting the **forceServerObjectId** flag.
  472. *
  473. * @method
  474. * @param {object[]} docs Documents to insert.
  475. * @param {object} [options] Optional settings.
  476. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  477. * @param {boolean} [options.ordered=true] If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails.
  478. * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver.
  479. * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead.
  480. * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead.
  481. * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead.
  482. * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings.
  483. * @param {boolean} [options.checkKeys=true] If true, will throw if bson documents start with `$` or include a `.` in any key value
  484. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
  485. * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
  486. * @param {ClientSession} [options.session] optional session to use for this operation
  487. * @param {Collection~insertWriteOpCallback} [callback] The command result callback
  488. * @return {Promise} returns Promise if no callback passed
  489. */
  490. Collection.prototype.insertMany = function(docs, options, callback) {
  491. if (typeof options === 'function') (callback = options), (options = {});
  492. options = options ? Object.assign({}, options) : { ordered: true };
  493. const insertManyOperation = new InsertManyOperation(this, docs, options);
  494. return executeOperation(this.s.topology, insertManyOperation, callback);
  495. };
  496. /**
  497. * @typedef {Object} Collection~BulkWriteOpResult
  498. * @property {number} insertedCount Number of documents inserted.
  499. * @property {number} matchedCount Number of documents matched for update.
  500. * @property {number} modifiedCount Number of documents modified.
  501. * @property {number} deletedCount Number of documents deleted.
  502. * @property {number} upsertedCount Number of documents upserted.
  503. * @property {object} insertedIds Inserted document generated Id's, hash key is the index of the originating operation
  504. * @property {object} upsertedIds Upserted document generated Id's, hash key is the index of the originating operation
  505. * @property {object} result The command result object.
  506. */
  507. /**
  508. * The callback format for inserts
  509. * @callback Collection~bulkWriteOpCallback
  510. * @param {BulkWriteError} error An error instance representing the error during the execution.
  511. * @param {Collection~BulkWriteOpResult} result The result object if the command was executed successfully.
  512. */
  513. /**
  514. * Perform a bulkWrite operation without a fluent API
  515. *
  516. * Legal operation types are
  517. *
  518. * { insertOne: { document: { a: 1 } } }
  519. *
  520. * { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } }
  521. *
  522. * { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } }
  523. *
  524. * { updateMany: { filter: {}, update: {$set: {"a.$[i].x": 5}}, arrayFilters: [{ "i.x": 5 }]} }
  525. *
  526. * { deleteOne: { filter: {c:1} } }
  527. *
  528. * { deleteMany: { filter: {c:1} } }
  529. *
  530. * { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true}}
  531. *
  532. * If documents passed in do not contain the **_id** field,
  533. * one will be added to each of the documents missing it by the driver, mutating the document. This behavior
  534. * can be overridden by setting the **forceServerObjectId** flag.
  535. *
  536. * @method
  537. * @param {object[]} operations Bulk operations to perform.
  538. * @param {object} [options] Optional settings.
  539. * @param {boolean} [options.ordered=true] Execute write operation in ordered or unordered fashion.
  540. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  541. * @param {object[]} [options.arrayFilters] Determines which array elements to modify for update operation in MongoDB 3.6 or higher.
  542. * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead.
  543. * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead.
  544. * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead.
  545. * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings.
  546. * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value
  547. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
  548. * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
  549. * @param {ClientSession} [options.session] optional session to use for this operation
  550. * @param {Collection~bulkWriteOpCallback} [callback] The command result callback
  551. * @return {Promise} returns Promise if no callback passed
  552. */
  553. Collection.prototype.bulkWrite = function(operations, options, callback) {
  554. if (typeof options === 'function') (callback = options), (options = {});
  555. options = options || { ordered: true };
  556. if (!Array.isArray(operations)) {
  557. throw MongoError.create({ message: 'operations must be an array of documents', driver: true });
  558. }
  559. const bulkWriteOperation = new BulkWriteOperation(this, operations, options);
  560. return executeOperation(this.s.topology, bulkWriteOperation, callback);
  561. };
  562. /**
  563. * @typedef {Object} Collection~WriteOpResult
  564. * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany
  565. * @property {object} connection The connection object used for the operation.
  566. * @property {object} result The command result object.
  567. */
  568. /**
  569. * The callback format for inserts
  570. * @callback Collection~writeOpCallback
  571. * @param {MongoError} error An error instance representing the error during the execution.
  572. * @param {Collection~WriteOpResult} result The result object if the command was executed successfully.
  573. */
  574. /**
  575. * @typedef {Object} Collection~insertWriteOpResult
  576. * @property {number} insertedCount The total amount of documents inserted.
  577. * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany
  578. * @property {Object.<Number, ObjectId>} insertedIds Map of the index of the inserted document to the id of the inserted document.
  579. * @property {object} connection The connection object used for the operation.
  580. * @property {object} result The raw command result object returned from MongoDB (content might vary by server version).
  581. * @property {number} result.ok Is 1 if the command executed correctly.
  582. * @property {number} result.n The total count of documents inserted.
  583. */
  584. /**
  585. * @typedef {Object} Collection~insertOneWriteOpResult
  586. * @property {number} insertedCount The total amount of documents inserted.
  587. * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany
  588. * @property {ObjectId} insertedId The driver generated ObjectId for the insert operation.
  589. * @property {object} connection The connection object used for the operation.
  590. * @property {object} result The raw command result object returned from MongoDB (content might vary by server version).
  591. * @property {number} result.ok Is 1 if the command executed correctly.
  592. * @property {number} result.n The total count of documents inserted.
  593. */
  594. /**
  595. * The callback format for inserts
  596. * @callback Collection~insertWriteOpCallback
  597. * @param {MongoError} error An error instance representing the error during the execution.
  598. * @param {Collection~insertWriteOpResult} result The result object if the command was executed successfully.
  599. */
  600. /**
  601. * The callback format for inserts
  602. * @callback Collection~insertOneWriteOpCallback
  603. * @param {MongoError} error An error instance representing the error during the execution.
  604. * @param {Collection~insertOneWriteOpResult} result The result object if the command was executed successfully.
  605. */
  606. /**
  607. * Inserts a single document or a an array of documents into MongoDB. If documents passed in do not contain the **_id** field,
  608. * one will be added to each of the documents missing it by the driver, mutating the document. This behavior
  609. * can be overridden by setting the **forceServerObjectId** flag.
  610. *
  611. * @method
  612. * @param {(object|object[])} docs Documents to insert.
  613. * @param {object} [options] Optional settings.
  614. * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead.
  615. * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead.
  616. * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead.
  617. * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings.
  618. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
  619. * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver.
  620. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  621. * @param {ClientSession} [options.session] optional session to use for this operation
  622. * @param {Collection~insertWriteOpCallback} [callback] The command result callback
  623. * @return {Promise} returns Promise if no callback passed
  624. * @deprecated Use insertOne, insertMany or bulkWrite
  625. */
  626. Collection.prototype.insert = deprecate(function(docs, options, callback) {
  627. if (typeof options === 'function') (callback = options), (options = {});
  628. options = options || { ordered: false };
  629. docs = !Array.isArray(docs) ? [docs] : docs;
  630. if (options.keepGoing === true) {
  631. options.ordered = false;
  632. }
  633. return this.insertMany(docs, options, callback);
  634. }, 'collection.insert is deprecated. Use insertOne, insertMany or bulkWrite instead.');
  635. /**
  636. * @typedef {Object} Collection~updateWriteOpResult
  637. * @property {Object} result The raw result returned from MongoDB. Will vary depending on server version.
  638. * @property {Number} result.ok Is 1 if the command executed correctly.
  639. * @property {Number} result.n The total count of documents scanned.
  640. * @property {Number} result.nModified The total count of documents modified.
  641. * @property {Object} connection The connection object used for the operation.
  642. * @property {Number} matchedCount The number of documents that matched the filter.
  643. * @property {Number} modifiedCount The number of documents that were modified.
  644. * @property {Number} upsertedCount The number of documents upserted.
  645. * @property {Object} upsertedId The upserted id.
  646. * @property {ObjectId} upsertedId._id The upserted _id returned from the server.
  647. * @property {Object} message The raw msg response wrapped in an internal class
  648. * @property {object[]} [ops] In a response to {@link Collection#replaceOne replaceOne}, contains the new value of the document on the server. This is the same document that was originally passed in, and is only here for legacy purposes.
  649. */
  650. /**
  651. * The callback format for inserts
  652. * @callback Collection~updateWriteOpCallback
  653. * @param {MongoError} error An error instance representing the error during the execution.
  654. * @param {Collection~updateWriteOpResult} result The result object if the command was executed successfully.
  655. */
  656. /**
  657. * Update a single document in a collection
  658. * @method
  659. * @param {object} filter The Filter used to select the document to update
  660. * @param {object} update The update operations to be applied to the document
  661. * @param {object} [options] Optional settings.
  662. * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators
  663. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  664. * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
  665. * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information.
  666. * @param {boolean} [options.upsert=false] When true, creates a new document if no document matches the query..
  667. * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead.
  668. * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead.
  669. * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead.
  670. * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings.
  671. * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value
  672. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
  673. * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
  674. * @param {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output.
  675. * @param {ClientSession} [options.session] optional session to use for this operation
  676. * @param {Collection~updateWriteOpCallback} [callback] The command result callback
  677. * @return {Promise} returns Promise if no callback passed
  678. */
  679. Collection.prototype.updateOne = function(filter, update, options, callback) {
  680. if (typeof options === 'function') (callback = options), (options = {});
  681. options = Object.assign({}, options);
  682. // Add ignoreUndefined
  683. if (this.s.options.ignoreUndefined) {
  684. options = Object.assign({}, options);
  685. options.ignoreUndefined = this.s.options.ignoreUndefined;
  686. }
  687. return executeOperation(
  688. this.s.topology,
  689. new UpdateOneOperation(this, filter, update, options),
  690. callback
  691. );
  692. };
  693. /**
  694. * Replace a document in a collection with another document
  695. * @method
  696. * @param {object} filter The Filter used to select the document to replace
  697. * @param {object} doc The Document that replaces the matching document
  698. * @param {object} [options] Optional settings.
  699. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  700. * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
  701. * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information.
  702. * @param {boolean} [options.upsert=false] When true, creates a new document if no document matches the query.
  703. * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead.
  704. * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead.
  705. * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead.
  706. * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings.
  707. * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value
  708. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
  709. * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
  710. * @param {ClientSession} [options.session] optional session to use for this operation
  711. * @param {Collection~updateWriteOpCallback} [callback] The command result callback
  712. * @return {Promise<Collection~updateWriteOpResult>} returns Promise if no callback passed
  713. */
  714. Collection.prototype.replaceOne = function(filter, doc, options, callback) {
  715. if (typeof options === 'function') (callback = options), (options = {});
  716. options = Object.assign({}, options);
  717. // Add ignoreUndefined
  718. if (this.s.options.ignoreUndefined) {
  719. options = Object.assign({}, options);
  720. options.ignoreUndefined = this.s.options.ignoreUndefined;
  721. }
  722. return executeOperation(
  723. this.s.topology,
  724. new ReplaceOneOperation(this, filter, doc, options),
  725. callback
  726. );
  727. };
  728. /**
  729. * Update multiple documents in a collection
  730. * @method
  731. * @param {object} filter The Filter used to select the documents to update
  732. * @param {object} update The update operations to be applied to the documents
  733. * @param {object} [options] Optional settings.
  734. * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators
  735. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  736. * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
  737. * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information.
  738. * @param {boolean} [options.upsert=false] When true, creates a new document if no document matches the query..
  739. * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead.
  740. * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead.
  741. * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead.
  742. * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings.
  743. * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value
  744. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
  745. * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
  746. * @param {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output.
  747. * @param {ClientSession} [options.session] optional session to use for this operation
  748. * @param {Collection~updateWriteOpCallback} [callback] The command result callback
  749. * @return {Promise<Collection~updateWriteOpResult>} returns Promise if no callback passed
  750. */
  751. Collection.prototype.updateMany = function(filter, update, options, callback) {
  752. if (typeof options === 'function') (callback = options), (options = {});
  753. options = Object.assign({}, options);
  754. // Add ignoreUndefined
  755. if (this.s.options.ignoreUndefined) {
  756. options = Object.assign({}, options);
  757. options.ignoreUndefined = this.s.options.ignoreUndefined;
  758. }
  759. return executeOperation(
  760. this.s.topology,
  761. new UpdateManyOperation(this, filter, update, options),
  762. callback
  763. );
  764. };
  765. /**
  766. * Updates documents.
  767. * @method
  768. * @param {object} selector The selector for the update operation.
  769. * @param {object} update The update operations to be applied to the documents
  770. * @param {object} [options] Optional settings.
  771. * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead.
  772. * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead.
  773. * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead.
  774. * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings.
  775. * @param {boolean} [options.upsert=false] Update operation is an upsert.
  776. * @param {boolean} [options.multi=false] Update one/all documents with operation.
  777. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  778. * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
  779. * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators
  780. * @param {ClientSession} [options.session] optional session to use for this operation
  781. * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information.
  782. * @param {Collection~writeOpCallback} [callback] The command result callback
  783. * @throws {MongoError}
  784. * @return {Promise} returns Promise if no callback passed
  785. * @deprecated use updateOne, updateMany or bulkWrite
  786. */
  787. Collection.prototype.update = deprecate(function(selector, update, options, callback) {
  788. if (typeof options === 'function') (callback = options), (options = {});
  789. options = options || {};
  790. // Add ignoreUndefined
  791. if (this.s.options.ignoreUndefined) {
  792. options = Object.assign({}, options);
  793. options.ignoreUndefined = this.s.options.ignoreUndefined;
  794. }
  795. return executeLegacyOperation(this.s.topology, updateDocuments, [
  796. this,
  797. selector,
  798. update,
  799. options,
  800. callback
  801. ]);
  802. }, 'collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead.');
  803. /**
  804. * @typedef {Object} Collection~deleteWriteOpResult
  805. * @property {Object} result The raw result returned from MongoDB. Will vary depending on server version.
  806. * @property {Number} result.ok Is 1 if the command executed correctly.
  807. * @property {Number} result.n The total count of documents deleted.
  808. * @property {Object} connection The connection object used for the operation.
  809. * @property {Number} deletedCount The number of documents deleted.
  810. */
  811. /**
  812. * The callback format for deletes
  813. * @callback Collection~deleteWriteOpCallback
  814. * @param {MongoError} error An error instance representing the error during the execution.
  815. * @param {Collection~deleteWriteOpResult} result The result object if the command was executed successfully.
  816. */
  817. /**
  818. * Delete a document from a collection
  819. * @method
  820. * @param {object} filter The Filter used to select the document to remove
  821. * @param {object} [options] Optional settings.
  822. * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
  823. * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead.
  824. * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead.
  825. * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead.
  826. * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings.
  827. * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value
  828. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
  829. * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
  830. * @param {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output.
  831. * @param {ClientSession} [options.session] optional session to use for this operation
  832. * @param {string|object} [options.hint] optional index hint for optimizing the filter query
  833. * @param {Collection~deleteWriteOpCallback} [callback] The command result callback
  834. * @return {Promise} returns Promise if no callback passed
  835. */
  836. Collection.prototype.deleteOne = function(filter, options, callback) {
  837. if (typeof options === 'function') (callback = options), (options = {});
  838. options = Object.assign({}, options);
  839. // Add ignoreUndefined
  840. if (this.s.options.ignoreUndefined) {
  841. options = Object.assign({}, options);
  842. options.ignoreUndefined = this.s.options.ignoreUndefined;
  843. }
  844. const deleteOneOperation = new DeleteOneOperation(this, filter, options);
  845. return executeOperation(this.s.topology, deleteOneOperation, callback);
  846. };
  847. Collection.prototype.removeOne = Collection.prototype.deleteOne;
  848. /**
  849. * Delete multiple documents from a collection
  850. * @method
  851. * @param {object} filter The Filter used to select the documents to remove
  852. * @param {object} [options] Optional settings.
  853. * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
  854. * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead.
  855. * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead.
  856. * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead.
  857. * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings.
  858. * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value
  859. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
  860. * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
  861. * @param {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output.
  862. * @param {ClientSession} [options.session] optional session to use for this operation
  863. * @param {string|object} [options.hint] optional index hint for optimizing the filter query
  864. * @param {Collection~deleteWriteOpCallback} [callback] The command result callback
  865. * @return {Promise} returns Promise if no callback passed
  866. */
  867. Collection.prototype.deleteMany = function(filter, options, callback) {
  868. if (typeof options === 'function') (callback = options), (options = {});
  869. options = Object.assign({}, options);
  870. // Add ignoreUndefined
  871. if (this.s.options.ignoreUndefined) {
  872. options = Object.assign({}, options);
  873. options.ignoreUndefined = this.s.options.ignoreUndefined;
  874. }
  875. const deleteManyOperation = new DeleteManyOperation(this, filter, options);
  876. return executeOperation(this.s.topology, deleteManyOperation, callback);
  877. };
  878. Collection.prototype.removeMany = Collection.prototype.deleteMany;
  879. /**
  880. * Remove documents.
  881. * @method
  882. * @param {object} selector The selector for the update operation.
  883. * @param {object} [options] Optional settings.
  884. * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
  885. * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead.
  886. * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead.
  887. * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead.
  888. * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings.
  889. * @param {boolean} [options.single=false] Removes the first document found.
  890. * @param {ClientSession} [options.session] optional session to use for this operation
  891. * @param {Collection~writeOpCallback} [callback] The command result callback
  892. * @return {Promise} returns Promise if no callback passed
  893. * @deprecated use deleteOne, deleteMany or bulkWrite
  894. */
  895. Collection.prototype.remove = deprecate(function(selector, options, callback) {
  896. if (typeof options === 'function') (callback = options), (options = {});
  897. options = options || {};
  898. // Add ignoreUndefined
  899. if (this.s.options.ignoreUndefined) {
  900. options = Object.assign({}, options);
  901. options.ignoreUndefined = this.s.options.ignoreUndefined;
  902. }
  903. return executeLegacyOperation(this.s.topology, removeDocuments, [
  904. this,
  905. selector,
  906. options,
  907. callback
  908. ]);
  909. }, 'collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.');
  910. /**
  911. * Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic
  912. * operators and update instead for more efficient operations.
  913. * @method
  914. * @param {object} doc Document to save
  915. * @param {object} [options] Optional settings.
  916. * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead.
  917. * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead.
  918. * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead.
  919. * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings.
  920. * @param {ClientSession} [options.session] optional session to use for this operation
  921. * @param {Collection~writeOpCallback} [callback] The command result callback
  922. * @return {Promise} returns Promise if no callback passed
  923. * @deprecated use insertOne, insertMany, updateOne or updateMany
  924. */
  925. Collection.prototype.save = deprecate(function(doc, options, callback) {
  926. if (typeof options === 'function') (callback = options), (options = {});
  927. options = options || {};
  928. // Add ignoreUndefined
  929. if (this.s.options.ignoreUndefined) {
  930. options = Object.assign({}, options);
  931. options.ignoreUndefined = this.s.options.ignoreUndefined;
  932. }
  933. return executeLegacyOperation(this.s.topology, save, [this, doc, options, callback]);
  934. }, 'collection.save is deprecated. Use insertOne, insertMany, updateOne, or updateMany instead.');
  935. /**
  936. * The callback format for results
  937. * @callback Collection~resultCallback
  938. * @param {MongoError} error An error instance representing the error during the execution.
  939. * @param {object} result The result object if the command was executed successfully.
  940. */
  941. /**
  942. * The callback format for an aggregation call
  943. * @callback Collection~aggregationCallback
  944. * @param {MongoError} error An error instance representing the error during the execution.
  945. * @param {AggregationCursor} cursor The cursor if the aggregation command was executed successfully.
  946. */
  947. /**
  948. * Fetches the first document that matches the query
  949. * @method
  950. * @param {object} query Query for find Operation
  951. * @param {object} [options] Optional settings.
  952. * @param {number} [options.limit=0] Sets the limit of documents returned in the query.
  953. * @param {(array|object)} [options.sort] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc.
  954. * @param {object} [options.projection] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1}
  955. * @param {object} [options.fields] **Deprecated** Use `options.projection` instead
  956. * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination).
  957. * @param {Object} [options.hint] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1}
  958. * @param {boolean} [options.snapshot=false] DEPRECATED: Snapshot query.
  959. * @param {boolean} [options.timeout=false] Specify if the cursor can timeout.
  960. * @param {boolean} [options.tailable=false] Specify if the cursor is tailable.
  961. * @param {number} [options.batchSize=1] Set the batchSize for the getMoreCommand when iterating over the query results.
  962. * @param {boolean} [options.returnKey=false] Only return the index key.
  963. * @param {number} [options.maxScan] DEPRECATED: Limit the number of items to scan.
  964. * @param {number} [options.min] Set index bounds.
  965. * @param {number} [options.max] Set index bounds.
  966. * @param {boolean} [options.showDiskLoc=false] Show disk location of results.
  967. * @param {string} [options.comment] You can put a $comment field on a query to make looking in the profiler logs simpler.
  968. * @param {boolean} [options.raw=false] Return document results as raw BSON buffers.
  969. * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution.
  970. * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types.
  971. * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers.
  972. * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  973. * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system
  974. * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query.
  975. * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
  976. * @param {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output.
  977. * @param {ClientSession} [options.session] optional session to use for this operation
  978. * @param {Collection~resultCallback} [callback] The command result callback
  979. * @return {Promise} returns Promise if no callback passed
  980. */
  981. Collection.prototype.findOne = deprecateOptions(
  982. {
  983. name: 'collection.find',
  984. deprecatedOptions: DEPRECATED_FIND_OPTIONS,
  985. optionsIndex: 1
  986. },
  987. function(query, options, callback) {
  988. if (typeof callback === 'object') {
  989. // TODO(MAJOR): throw in the future
  990. emitWarningOnce('Third parameter to `findOne()` must be a callback or undefined');
  991. }
  992. if (typeof query === 'function') (callback = query), (query = {}), (options = {});
  993. if (typeof options === 'function') (callback = options), (options = {});
  994. query = query || {};
  995. options = options || {};
  996. const findOneOperation = new FindOneOperation(this, query, options);
  997. return executeOperation(this.s.topology, findOneOperation, callback);
  998. }
  999. );
  1000. /**
  1001. * The callback format for the collection method, must be used if strict is specified
  1002. * @callback Collection~collectionResultCallback
  1003. * @param {MongoError} error An error instance representing the error during the execution.
  1004. * @param {Collection} collection The collection instance.
  1005. */
  1006. /**
  1007. * Rename the collection.
  1008. *
  1009. * @method
  1010. * @param {string} newName New name of of the collection.
  1011. * @param {object} [options] Optional settings.
  1012. * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists.
  1013. * @param {ClientSession} [options.session] optional session to use for this operation
  1014. * @param {Collection~collectionResultCallback} [callback] The results callback
  1015. * @return {Promise} returns Promise if no callback passed
  1016. */
  1017. Collection.prototype.rename = function(newName, options, callback) {
  1018. if (typeof options === 'function') (callback = options), (options = {});
  1019. options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY });
  1020. const renameOperation = new RenameOperation(this, newName, options);
  1021. return executeOperation(this.s.topology, renameOperation, callback);
  1022. };
  1023. /**
  1024. * Drop the collection from the database, removing it permanently. New accesses will create a new collection.
  1025. *
  1026. * @method
  1027. * @param {object} [options] Optional settings.
  1028. * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead.
  1029. * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead.
  1030. * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead.
  1031. * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings.
  1032. * @param {ClientSession} [options.session] optional session to use for this operation
  1033. * @param {Collection~resultCallback} [callback] The results callback
  1034. * @return {Promise} returns Promise if no callback passed
  1035. */
  1036. Collection.prototype.drop = function(options, callback) {
  1037. if (typeof options === 'function') (callback = options), (options = {});
  1038. options = options || {};
  1039. const dropCollectionOperation = new DropCollectionOperation(
  1040. this.s.db,
  1041. this.collectionName,
  1042. options
  1043. );
  1044. return executeOperation(this.s.topology, dropCollectionOperation, callback);
  1045. };
  1046. /**
  1047. * Returns the options of the collection.
  1048. *
  1049. * @method
  1050. * @param {Object} [options] Optional settings
  1051. * @param {ClientSession} [options.session] optional session to use for this operation
  1052. * @param {Collection~resultCallback} [callback] The results callback
  1053. * @return {Promise} returns Promise if no callback passed
  1054. */
  1055. Collection.prototype.options = function(opts, callback) {
  1056. if (typeof opts === 'function') (callback = opts), (opts = {});
  1057. opts = opts || {};
  1058. const optionsOperation = new OptionsOperation(this, opts);
  1059. return executeOperation(this.s.topology, optionsOperation, callback);
  1060. };
  1061. /**
  1062. * Returns if the collection is a capped collection
  1063. *
  1064. * @method
  1065. * @param {Object} [options] Optional settings
  1066. * @param {ClientSession} [options.session] optional session to use for this operation
  1067. * @param {Collection~resultCallback} [callback] The results callback
  1068. * @return {Promise} returns Promise if no callback passed
  1069. */
  1070. Collection.prototype.isCapped = function(options, callback) {
  1071. if (typeof options === 'function') (callback = options), (options = {});
  1072. options = options || {};
  1073. const isCappedOperation = new IsCappedOperation(this, options);
  1074. return executeOperation(this.s.topology, isCappedOperation, callback);
  1075. };
  1076. /**
  1077. * Creates an index on the db and collection collection.
  1078. * @method
  1079. * @param {(string|array|object)} fieldOrSpec Defines the index.
  1080. * @param {object} [options] Optional settings.
  1081. * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead.
  1082. * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead.
  1083. * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead.
  1084. * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings.
  1085. * @param {boolean} [options.unique=false] Creates an unique index.
  1086. * @param {boolean} [options.sparse=false] Creates a sparse index.
  1087. * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible.
  1088. * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value
  1089. * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates.
  1090. * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates.
  1091. * @param {number} [options.v] Specify the format version of the indexes.
  1092. * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
  1093. * @param {string} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes)
  1094. * @param {object} [options.partialFilterExpression] Creates a partial index based on the given filter object (MongoDB 3.2 or higher)
  1095. * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
  1096. * @param {ClientSession} [options.session] optional session to use for this operation
  1097. * @param {(number|string)} [options.commitQuorum] (MongoDB 4.4. or higher) Specifies how many data-bearing members of a replica set, including the primary, must complete the index builds successfully before the primary marks the indexes as ready. This option accepts the same values for the "w" field in a write concern plus "votingMembers", which indicates all voting data-bearing nodes.
  1098. * @param {Collection~resultCallback} [callback] The command result callback
  1099. * @return {Promise} returns Promise if no callback passed
  1100. * @example
  1101. * const collection = client.db('foo').collection('bar');
  1102. *
  1103. * await collection.createIndex({ a: 1, b: -1 });
  1104. *
  1105. * // Alternate syntax for { c: 1, d: -1 } that ensures order of indexes
  1106. * await collection.createIndex([ [c, 1], [d, -1] ]);
  1107. *
  1108. * // Equivalent to { e: 1 }
  1109. * await collection.createIndex('e');
  1110. *
  1111. * // Equivalent to { f: 1, g: 1 }
  1112. * await collection.createIndex(['f', 'g'])
  1113. *
  1114. * // Equivalent to { h: 1, i: -1 }
  1115. * await collection.createIndex([ { h: 1 }, { i: -1 } ]);
  1116. *
  1117. * // Equivalent to { j: 1, k: -1, l: 2d }
  1118. * await collection.createIndex(['j', ['k', -1], { l: '2d' }])
  1119. */
  1120. Collection.prototype.createIndex = function(fieldOrSpec, options, callback) {
  1121. if (typeof options === 'function') (callback = options), (options = {});
  1122. options = options || {};
  1123. const createIndexesOperation = new CreateIndexesOperation(
  1124. this,
  1125. this.collectionName,
  1126. fieldOrSpec,
  1127. options
  1128. );
  1129. return executeOperation(this.s.topology, createIndexesOperation, callback);
  1130. };
  1131. /**
  1132. * @typedef {object} Collection~IndexDefinition
  1133. * @description A definition for an index. Used by the createIndex command.
  1134. * @see https://docs.mongodb.com/manual/reference/command/createIndexes/
  1135. */
  1136. /**
  1137. * Creates multiple indexes in the collection, this method is only supported for
  1138. * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported
  1139. * error.
  1140. *
  1141. * **Note**: Unlike {@link Collection#createIndex createIndex}, this function takes in raw index specifications.
  1142. * Index specifications are defined {@link http://docs.mongodb.org/manual/reference/command/createIndexes/ here}.
  1143. *
  1144. * @method
  1145. * @param {Collection~IndexDefinition[]} indexSpecs An array of index specifications to be created
  1146. * @param {Object} [options] Optional settings
  1147. * @param {ClientSession} [options.session] optional session to use for this operation
  1148. * @param {(number|string)} [options.commitQuorum] (MongoDB 4.4. or higher) Specifies how many data-bearing members of a replica set, including the primary, must complete the index builds successfully before the primary marks the indexes as ready. This option accepts the same values for the "w" field in a write concern plus "votingMembers", which indicates all voting data-bearing nodes.
  1149. * @param {Collection~resultCallback} [callback] The command result callback
  1150. * @return {Promise} returns Promise if no callback passed
  1151. * @example
  1152. * const collection = client.db('foo').collection('bar');
  1153. * await collection.createIndexes([
  1154. * // Simple index on field fizz
  1155. * {
  1156. * key: { fizz: 1 },
  1157. * }
  1158. * // wildcard index
  1159. * {
  1160. * key: { '$**': 1 }
  1161. * },
  1162. * // named index on darmok and jalad
  1163. * {
  1164. * key: { darmok: 1, jalad: -1 }
  1165. * name: 'tanagra'
  1166. * }
  1167. * ]);
  1168. */
  1169. Collection.prototype.createIndexes = function(indexSpecs, options, callback) {
  1170. if (typeof options === 'function') (callback = options), (options = {});
  1171. options = options ? Object.assign({}, options) : {};
  1172. if (typeof options.maxTimeMS !== 'number') delete options.maxTimeMS;
  1173. const createIndexesOperation = new CreateIndexesOperation(
  1174. this,
  1175. this.collectionName,
  1176. indexSpecs,
  1177. options
  1178. );
  1179. return executeOperation(this.s.topology, createIndexesOperation, callback);
  1180. };
  1181. /**
  1182. * Drops an index from this collection.
  1183. * @method
  1184. * @param {string} indexName Name of the index to drop.
  1185. * @param {object} [options] Optional settings.
  1186. * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead.
  1187. * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead.
  1188. * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead.
  1189. * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings.
  1190. * @param {ClientSession} [options.session] optional session to use for this operation
  1191. * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query.
  1192. * @param {Collection~resultCallback} [callback] The command result callback
  1193. * @return {Promise} returns Promise if no callback passed
  1194. */
  1195. Collection.prototype.dropIndex = function(indexName, options, callback) {
  1196. const args = Array.prototype.slice.call(arguments, 1);
  1197. callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
  1198. options = args.length ? args.shift() || {} : {};
  1199. // Run only against primary
  1200. options.readPreference = ReadPreference.PRIMARY;
  1201. const dropIndexOperation = new DropIndexOperation(this, indexName, options);
  1202. return executeOperation(this.s.topology, dropIndexOperation, callback);
  1203. };
  1204. /**
  1205. * Drops all indexes from this collection.
  1206. * @method
  1207. * @param {Object} [options] Optional settings
  1208. * @param {ClientSession} [options.session] optional session to use for this operation
  1209. * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query.
  1210. * @param {Collection~resultCallback} [callback] The command result callback
  1211. * @return {Promise} returns Promise if no callback passed
  1212. */
  1213. Collection.prototype.dropIndexes = function(options, callback) {
  1214. if (typeof options === 'function') (callback = options), (options = {});
  1215. options = options ? Object.assign({}, options) : {};
  1216. if (typeof options.maxTimeMS !== 'number') delete options.maxTimeMS;
  1217. const dropIndexesOperation = new DropIndexesOperation(this, options);
  1218. return executeOperation(this.s.topology, dropIndexesOperation, callback);
  1219. };
  1220. /**
  1221. * Drops all indexes from this collection.
  1222. * @method
  1223. * @deprecated use dropIndexes
  1224. * @param {Collection~resultCallback} callback The command result callback
  1225. * @return {Promise} returns Promise if no [callback] passed
  1226. */
  1227. Collection.prototype.dropAllIndexes = deprecate(
  1228. Collection.prototype.dropIndexes,
  1229. 'collection.dropAllIndexes is deprecated. Use dropIndexes instead.'
  1230. );
  1231. /**
  1232. * Reindex all indexes on the collection
  1233. * Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections.
  1234. * @method
  1235. * @deprecated use db.command instead
  1236. * @param {Object} [options] Optional settings
  1237. * @param {ClientSession} [options.session] optional session to use for this operation
  1238. * @param {Collection~resultCallback} [callback] The command result callback
  1239. * @return {Promise} returns Promise if no callback passed
  1240. */
  1241. Collection.prototype.reIndex = deprecate(function(options, callback) {
  1242. if (typeof options === 'function') (callback = options), (options = {});
  1243. options = options || {};
  1244. const reIndexOperation = new ReIndexOperation(this, options);
  1245. return executeOperation(this.s.topology, reIndexOperation, callback);
  1246. }, 'collection.reIndex is deprecated. Use db.command instead.');
  1247. /**
  1248. * Get the list of all indexes information for the collection.
  1249. *
  1250. * @method
  1251. * @param {object} [options] Optional settings.
  1252. * @param {number} [options.batchSize=1000] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection
  1253. * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  1254. * @param {ClientSession} [options.session] optional session to use for this operation
  1255. * @return {CommandCursor}
  1256. */
  1257. Collection.prototype.listIndexes = function(options) {
  1258. const cursor = new CommandCursor(
  1259. this.s.topology,
  1260. new ListIndexesOperation(this, options),
  1261. options
  1262. );
  1263. return cursor;
  1264. };
  1265. /**
  1266. * Ensures that an index exists, if it does not it creates it
  1267. * @method
  1268. * @deprecated use createIndexes instead
  1269. * @param {(string|object)} fieldOrSpec Defines the index.
  1270. * @param {object} [options] Optional settings.
  1271. * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead.
  1272. * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead.
  1273. * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead.
  1274. * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings.
  1275. * @param {boolean} [options.unique=false] Creates an unique index.
  1276. * @param {boolean} [options.sparse=false] Creates a sparse index.
  1277. * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible.
  1278. * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value
  1279. * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates.
  1280. * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates.
  1281. * @param {number} [options.v] Specify the format version of the indexes.
  1282. * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
  1283. * @param {number} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes)
  1284. * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
  1285. * @param {ClientSession} [options.session] optional session to use for this operation
  1286. * @param {Collection~resultCallback} [callback] The command result callback
  1287. * @return {Promise} returns Promise if no callback passed
  1288. */
  1289. Collection.prototype.ensureIndex = deprecate(function(fieldOrSpec, options, callback) {
  1290. if (typeof options === 'function') (callback = options), (options = {});
  1291. options = options || {};
  1292. return executeLegacyOperation(this.s.topology, ensureIndex, [
  1293. this,
  1294. fieldOrSpec,
  1295. options,
  1296. callback
  1297. ]);
  1298. }, 'collection.ensureIndex is deprecated. Use createIndexes instead.');
  1299. /**
  1300. * Checks if one or more indexes exist on the collection, fails on first non-existing index
  1301. * @method
  1302. * @param {(string|array)} indexes One or more index names to check.
  1303. * @param {Object} [options] Optional settings
  1304. * @param {ClientSession} [options.session] optional session to use for this operation
  1305. * @param {Collection~resultCallback} [callback] The command result callback
  1306. * @return {Promise} returns Promise if no callback passed
  1307. */
  1308. Collection.prototype.indexExists = function(indexes, options, callback) {
  1309. if (typeof options === 'function') (callback = options), (options = {});
  1310. options = options || {};
  1311. const indexExistsOperation = new IndexExistsOperation(this, indexes, options);
  1312. return executeOperation(this.s.topology, indexExistsOperation, callback);
  1313. };
  1314. /**
  1315. * Retrieves this collections index info.
  1316. * @method
  1317. * @param {object} [options] Optional settings.
  1318. * @param {boolean} [options.full=false] Returns the full raw index information.
  1319. * @param {ClientSession} [options.session] optional session to use for this operation
  1320. * @param {Collection~resultCallback} [callback] The command result callback
  1321. * @return {Promise} returns Promise if no callback passed
  1322. */
  1323. Collection.prototype.indexInformation = function(options, callback) {
  1324. const args = Array.prototype.slice.call(arguments, 0);
  1325. callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
  1326. options = args.length ? args.shift() || {} : {};
  1327. const indexInformationOperation = new IndexInformationOperation(
  1328. this.s.db,
  1329. this.collectionName,
  1330. options
  1331. );
  1332. return executeOperation(this.s.topology, indexInformationOperation, callback);
  1333. };
  1334. /**
  1335. * The callback format for results
  1336. * @callback Collection~countCallback
  1337. * @param {MongoError} error An error instance representing the error during the execution.
  1338. * @param {number} result The count of documents that matched the query.
  1339. */
  1340. /**
  1341. * An estimated count of matching documents in the db to a query.
  1342. *
  1343. * **NOTE:** This method has been deprecated, since it does not provide an accurate count of the documents
  1344. * in a collection. To obtain an accurate count of documents in the collection, use {@link Collection#countDocuments countDocuments}.
  1345. * To obtain an estimated count of all documents in the collection, use {@link Collection#estimatedDocumentCount estimatedDocumentCount}.
  1346. *
  1347. * @method
  1348. * @param {object} [query={}] The query for the count.
  1349. * @param {object} [options] Optional settings.
  1350. * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.
  1351. * @param {boolean} [options.limit] The limit of documents to count.
  1352. * @param {boolean} [options.skip] The number of documents to skip for the count.
  1353. * @param {string} [options.hint] An index name hint for the query.
  1354. * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  1355. * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query.
  1356. * @param {ClientSession} [options.session] optional session to use for this operation
  1357. * @param {Collection~countCallback} [callback] The command result callback
  1358. * @return {Promise} returns Promise if no callback passed
  1359. * @deprecated use {@link Collection#countDocuments countDocuments} or {@link Collection#estimatedDocumentCount estimatedDocumentCount} instead
  1360. */
  1361. Collection.prototype.count = deprecate(function(query, options, callback) {
  1362. const args = Array.prototype.slice.call(arguments, 0);
  1363. callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
  1364. query = args.length ? args.shift() || {} : {};
  1365. options = args.length ? args.shift() || {} : {};
  1366. if (typeof options === 'function') (callback = options), (options = {});
  1367. options = options || {};
  1368. return executeOperation(
  1369. this.s.topology,
  1370. new EstimatedDocumentCountOperation(this, query, options),
  1371. callback
  1372. );
  1373. }, 'collection.count is deprecated, and will be removed in a future version.' +
  1374. ' Use Collection.countDocuments or Collection.estimatedDocumentCount instead');
  1375. /**
  1376. * Gets an estimate of the count of documents in a collection using collection metadata.
  1377. *
  1378. * @method
  1379. * @param {object} [options] Optional settings.
  1380. * @param {number} [options.maxTimeMS] The maximum amount of time to allow the operation to run.
  1381. * @param {Collection~countCallback} [callback] The command result callback.
  1382. * @return {Promise} returns Promise if no callback passed.
  1383. */
  1384. Collection.prototype.estimatedDocumentCount = function(options, callback) {
  1385. if (typeof options === 'function') (callback = options), (options = {});
  1386. options = options || {};
  1387. const estimatedDocumentCountOperation = new EstimatedDocumentCountOperation(this, options);
  1388. return executeOperation(this.s.topology, estimatedDocumentCountOperation, callback);
  1389. };
  1390. /**
  1391. * Gets the number of documents matching the filter.
  1392. * For a fast count of the total documents in a collection see {@link Collection#estimatedDocumentCount estimatedDocumentCount}.
  1393. * **Note**: When migrating from {@link Collection#count count} to {@link Collection#countDocuments countDocuments}
  1394. * the following query operators must be replaced:
  1395. *
  1396. * | Operator | Replacement |
  1397. * | -------- | ----------- |
  1398. * | `$where` | [`$expr`][1] |
  1399. * | `$near` | [`$geoWithin`][2] with [`$center`][3] |
  1400. * | `$nearSphere` | [`$geoWithin`][2] with [`$centerSphere`][4] |
  1401. *
  1402. * [1]: https://docs.mongodb.com/manual/reference/operator/query/expr/
  1403. * [2]: https://docs.mongodb.com/manual/reference/operator/query/geoWithin/
  1404. * [3]: https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center
  1405. * [4]: https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere
  1406. *
  1407. * @param {object} [query] the query for the count
  1408. * @param {object} [options] Optional settings.
  1409. * @param {object} [options.collation] Specifies a collation.
  1410. * @param {string|object} [options.hint] The index to use.
  1411. * @param {number} [options.limit] The maximum number of document to count.
  1412. * @param {number} [options.maxTimeMS] The maximum amount of time to allow the operation to run.
  1413. * @param {number} [options.skip] The number of documents to skip before counting.
  1414. * @param {Collection~countCallback} [callback] The command result callback.
  1415. * @return {Promise} returns Promise if no callback passed.
  1416. * @see https://docs.mongodb.com/manual/reference/operator/query/expr/
  1417. * @see https://docs.mongodb.com/manual/reference/operator/query/geoWithin/
  1418. * @see https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center
  1419. * @see https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere
  1420. */
  1421. Collection.prototype.countDocuments = function(query, options, callback) {
  1422. const args = Array.prototype.slice.call(arguments, 0);
  1423. callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
  1424. query = args.length ? args.shift() || {} : {};
  1425. options = args.length ? args.shift() || {} : {};
  1426. const countDocumentsOperation = new CountDocumentsOperation(this, query, options);
  1427. return executeOperation(this.s.topology, countDocumentsOperation, callback);
  1428. };
  1429. /**
  1430. * The distinct command returns a list of distinct values for the given key across a collection.
  1431. * @method
  1432. * @param {string} key Field of the document to find distinct values for.
  1433. * @param {object} [query] The query for filtering the set of documents to which we apply the distinct filter.
  1434. * @param {object} [options] Optional settings.
  1435. * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  1436. * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query.
  1437. * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.
  1438. * @param {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output.
  1439. * @param {ClientSession} [options.session] optional session to use for this operation
  1440. * @param {Collection~resultCallback} [callback] The command result callback
  1441. * @return {Promise} returns Promise if no callback passed
  1442. */
  1443. Collection.prototype.distinct = function(key, query, options, callback) {
  1444. const args = Array.prototype.slice.call(arguments, 1);
  1445. callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
  1446. const queryOption = args.length ? args.shift() || {} : {};
  1447. const optionsOption = args.length ? args.shift() || {} : {};
  1448. const distinctOperation = new DistinctOperation(this, key, queryOption, optionsOption);
  1449. return executeOperation(this.s.topology, distinctOperation, callback);
  1450. };
  1451. /**
  1452. * Retrieve all the indexes on the collection.
  1453. * @method
  1454. * @param {Object} [options] Optional settings
  1455. * @param {ClientSession} [options.session] optional session to use for this operation
  1456. * @param {Collection~resultCallback} [callback] The command result callback
  1457. * @return {Promise} returns Promise if no callback passed
  1458. */
  1459. Collection.prototype.indexes = function(options, callback) {
  1460. if (typeof options === 'function') (callback = options), (options = {});
  1461. options = options || {};
  1462. const indexesOperation = new IndexesOperation(this, options);
  1463. return executeOperation(this.s.topology, indexesOperation, callback);
  1464. };
  1465. /**
  1466. * Get all the collection statistics.
  1467. *
  1468. * @method
  1469. * @param {object} [options] Optional settings.
  1470. * @param {number} [options.scale] Divide the returned sizes by scale value.
  1471. * @param {ClientSession} [options.session] optional session to use for this operation
  1472. * @param {Collection~resultCallback} [callback] The collection result callback
  1473. * @return {Promise} returns Promise if no callback passed
  1474. */
  1475. Collection.prototype.stats = function(options, callback) {
  1476. const args = Array.prototype.slice.call(arguments, 0);
  1477. callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
  1478. options = args.length ? args.shift() || {} : {};
  1479. const statsOperation = new StatsOperation(this, options);
  1480. return executeOperation(this.s.topology, statsOperation, callback);
  1481. };
  1482. /**
  1483. * @typedef {Object} Collection~findAndModifyWriteOpResult
  1484. * @property {object} value Document returned from the `findAndModify` command. If no documents were found, `value` will be `null` by default even if a document was upserted unless `returnDocument` is specified as `'after'`, in which case the upserted document will be returned.
  1485. * @property {object} lastErrorObject The raw lastErrorObject returned from the command. See {@link https://docs.mongodb.com/manual/reference/command/findAndModify/index.html#lasterrorobject|findAndModify command documentation}.
  1486. * @property {Number} ok Is 1 if the command executed correctly.
  1487. */
  1488. /**
  1489. * The callback format for inserts
  1490. * @callback Collection~findAndModifyCallback
  1491. * @param {MongoError} error An error instance representing the error during the execution.
  1492. * @param {Collection~findAndModifyWriteOpResult} result The result object if the command was executed successfully.
  1493. */
  1494. /**
  1495. * Find a document and delete it in one atomic operation. Requires a write lock for the duration of the operation.
  1496. *
  1497. * @method
  1498. * @param {object} filter The Filter used to select the document to remove
  1499. * @param {object} [options] Optional settings.
  1500. * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
  1501. * @param {object} [options.projection] Limits the fields to return for all matching documents.
  1502. * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents.
  1503. * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run.
  1504. * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value
  1505. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
  1506. * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
  1507. * @param {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output.
  1508. * @param {ClientSession} [options.session] optional session to use for this operation
  1509. * @param {Collection~findAndModifyCallback} [callback] The collection result callback
  1510. * @return {Promise<Collection~findAndModifyWriteOpResultObject>} returns Promise if no callback passed
  1511. */
  1512. Collection.prototype.findOneAndDelete = function(filter, options, callback) {
  1513. if (typeof options === 'function') (callback = options), (options = {});
  1514. options = options || {};
  1515. // Add ignoreUndefined
  1516. if (this.s.options.ignoreUndefined) {
  1517. options = Object.assign({}, options);
  1518. options.ignoreUndefined = this.s.options.ignoreUndefined;
  1519. }
  1520. return executeOperation(
  1521. this.s.topology,
  1522. new FindOneAndDeleteOperation(this, filter, options),
  1523. callback
  1524. );
  1525. };
  1526. /**
  1527. * Find a document and replace it in one atomic operation. Requires a write lock for the duration of the operation.
  1528. *
  1529. * @method
  1530. * @param {object} filter The Filter used to select the document to replace
  1531. * @param {object} replacement The Document that replaces the matching document
  1532. * @param {object} [options] Optional settings.
  1533. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  1534. * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
  1535. * @param {string|object} [options.hint] An optional index to use for this operation
  1536. * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run.
  1537. * @param {object} [options.projection] Limits the fields to return for all matching documents.
  1538. * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents.
  1539. * @param {boolean} [options.upsert=false] Upsert the document if it does not exist.
  1540. * @param {'before'|'after'} [options.returnDocument='before'] When set to `'after'`, returns the updated document rather than the original. The default is `'before'`.
  1541. * @param {boolean} [options.returnOriginal=true] **Deprecated** Use `options.returnDocument` instead.
  1542. * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value
  1543. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
  1544. * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
  1545. * @param {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output.
  1546. * @param {ClientSession} [options.session] optional session to use for this operation
  1547. * @param {Collection~findAndModifyCallback} [callback] The collection result callback
  1548. * @return {Promise<Collection~findAndModifyWriteOpResultObject>} returns Promise if no callback passed
  1549. */
  1550. Collection.prototype.findOneAndReplace = deprecateOptions(
  1551. {
  1552. name: 'collection.findOneAndReplace',
  1553. deprecatedOptions: ['returnOriginal'],
  1554. optionsIndex: 2
  1555. },
  1556. function(filter, replacement, options, callback) {
  1557. if (typeof options === 'function') (callback = options), (options = {});
  1558. options = options || {};
  1559. // Add ignoreUndefined
  1560. if (this.s.options.ignoreUndefined) {
  1561. options = Object.assign({}, options);
  1562. options.ignoreUndefined = this.s.options.ignoreUndefined;
  1563. }
  1564. return executeOperation(
  1565. this.s.topology,
  1566. new FindOneAndReplaceOperation(this, filter, replacement, options),
  1567. callback
  1568. );
  1569. }
  1570. );
  1571. /**
  1572. * Find a document and update it in one atomic operation. Requires a write lock for the duration of the operation.
  1573. *
  1574. * @method
  1575. * @param {object} filter The Filter used to select the document to update
  1576. * @param {object} update Update operations to be performed on the document
  1577. * @param {object} [options] Optional settings.
  1578. * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators
  1579. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  1580. * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
  1581. * @param {string|object} [options.hint] An optional index to use for this operation
  1582. * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run.
  1583. * @param {object} [options.projection] Limits the fields to return for all matching documents.
  1584. * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents.
  1585. * @param {boolean} [options.upsert=false] Upsert the document if it does not exist.
  1586. * @param {'before'|'after'} [options.returnDocument='before'] When set to `'after'`, returns the updated document rather than the original. The default is `'before'`.
  1587. * @param {boolean} [options.returnOriginal=true] **Deprecated** Use `options.returnDocument` instead.
  1588. * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value
  1589. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
  1590. * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
  1591. * @param {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output.
  1592. * @param {ClientSession} [options.session] An ptional session to use for this operation
  1593. * @param {Collection~findAndModifyCallback} [callback] The collection result callback
  1594. * @return {Promise<Collection~findAndModifyWriteOpResultObject>} returns Promise if no callback passed
  1595. */
  1596. Collection.prototype.findOneAndUpdate = deprecateOptions(
  1597. {
  1598. name: 'collection.findOneAndUpdate',
  1599. deprecatedOptions: ['returnOriginal'],
  1600. optionsIndex: 2
  1601. },
  1602. function(filter, update, options, callback) {
  1603. if (typeof options === 'function') (callback = options), (options = {});
  1604. options = options || {};
  1605. // Add ignoreUndefined
  1606. if (this.s.options.ignoreUndefined) {
  1607. options = Object.assign({}, options);
  1608. options.ignoreUndefined = this.s.options.ignoreUndefined;
  1609. }
  1610. return executeOperation(
  1611. this.s.topology,
  1612. new FindOneAndUpdateOperation(this, filter, update, options),
  1613. callback
  1614. );
  1615. }
  1616. );
  1617. /**
  1618. * Find and update a document.
  1619. * @method
  1620. * @param {object} query Query object to locate the object to modify.
  1621. * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate.
  1622. * @param {object} doc The fields/vals to be updated.
  1623. * @param {object} [options] Optional settings.
  1624. * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead.
  1625. * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead.
  1626. * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead.
  1627. * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings.
  1628. * @param {boolean} [options.remove=false] Set to true to remove the object before returning.
  1629. * @param {boolean} [options.upsert=false] Perform an upsert operation.
  1630. * @param {boolean} [options.new=false] Set to true if you want to return the modified object rather than the original. Ignored for remove.
  1631. * @param {object} [options.projection] Object containing the field projection for the result returned from the operation.
  1632. * @param {object} [options.fields] **Deprecated** Use `options.projection` instead
  1633. * @param {ClientSession} [options.session] optional session to use for this operation
  1634. * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators
  1635. * @param {Collection~findAndModifyCallback} [callback] The command result callback
  1636. * @return {Promise} returns Promise if no callback passed
  1637. * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead
  1638. */
  1639. Collection.prototype.findAndModify = deprecate(
  1640. _findAndModify,
  1641. 'collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead.'
  1642. );
  1643. /**
  1644. * @ignore
  1645. */
  1646. Collection.prototype._findAndModify = _findAndModify;
  1647. function _findAndModify(query, sort, doc, options, callback) {
  1648. const args = Array.prototype.slice.call(arguments, 1);
  1649. callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
  1650. sort = args.length ? args.shift() || [] : [];
  1651. doc = args.length ? args.shift() : null;
  1652. options = args.length ? args.shift() || {} : {};
  1653. // Clone options
  1654. options = Object.assign({}, options);
  1655. // Force read preference primary
  1656. options.readPreference = ReadPreference.PRIMARY;
  1657. return executeOperation(
  1658. this.s.topology,
  1659. new FindAndModifyOperation(this, query, sort, doc, options),
  1660. callback
  1661. );
  1662. }
  1663. /**
  1664. * Find and remove a document.
  1665. * @method
  1666. * @param {object} query Query object to locate the object to modify.
  1667. * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate.
  1668. * @param {object} [options] Optional settings.
  1669. * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead.
  1670. * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead.
  1671. * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead.
  1672. * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings.
  1673. * @param {ClientSession} [options.session] optional session to use for this operation
  1674. * @param {Collection~resultCallback} [callback] The command result callback
  1675. * @return {Promise} returns Promise if no callback passed
  1676. * @deprecated use findOneAndDelete instead
  1677. */
  1678. Collection.prototype.findAndRemove = deprecate(function(query, sort, options, callback) {
  1679. const args = Array.prototype.slice.call(arguments, 1);
  1680. callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
  1681. sort = args.length ? args.shift() || [] : [];
  1682. options = args.length ? args.shift() || {} : {};
  1683. // Add the remove option
  1684. options.remove = true;
  1685. return executeOperation(
  1686. this.s.topology,
  1687. new FindAndModifyOperation(this, query, sort, null, options),
  1688. callback
  1689. );
  1690. }, 'collection.findAndRemove is deprecated. Use findOneAndDelete instead.');
  1691. /**
  1692. * Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2
  1693. * @method
  1694. * @param {object} [pipeline=[]] Array containing all the aggregation framework commands for the execution.
  1695. * @param {object} [options] Optional settings.
  1696. * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  1697. * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.
  1698. * @param {object} [options.cursor] Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor.
  1699. * @param {number} [options.cursor.batchSize=1000] Deprecated. Use `options.batchSize`
  1700. * @param {boolean} [options.allowDiskUse=false] allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >).
  1701. * @param {number} [options.maxTimeMS] maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point.
  1702. * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query.
  1703. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  1704. * @param {boolean} [options.raw=false] Return document results as raw BSON buffers.
  1705. * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution.
  1706. * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types.
  1707. * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers.
  1708. * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.
  1709. * @param {string} [options.comment] Add a comment to an aggregation command
  1710. * @param {string|object} [options.hint] Add an index selection hint to an aggregation command
  1711. * @param {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output.
  1712. * @param {ClientSession} [options.session] optional session to use for this operation
  1713. * @param {Collection~aggregationCallback} callback The command result callback
  1714. * @return {(null|AggregationCursor)}
  1715. */
  1716. Collection.prototype.aggregate = function(pipeline, options, callback) {
  1717. if (Array.isArray(pipeline)) {
  1718. // Set up callback if one is provided
  1719. if (typeof options === 'function') {
  1720. callback = options;
  1721. options = {};
  1722. }
  1723. // If we have no options or callback we are doing
  1724. // a cursor based aggregation
  1725. if (options == null && callback == null) {
  1726. options = {};
  1727. }
  1728. } else {
  1729. // Aggregation pipeline passed as arguments on the method
  1730. const args = Array.prototype.slice.call(arguments, 0);
  1731. // Get the callback
  1732. callback = args.pop();
  1733. // Get the possible options object
  1734. const opts = args[args.length - 1];
  1735. // If it contains any of the admissible options pop it of the args
  1736. options =
  1737. opts &&
  1738. (opts.readPreference ||
  1739. opts.explain ||
  1740. opts.cursor ||
  1741. opts.out ||
  1742. opts.maxTimeMS ||
  1743. opts.hint ||
  1744. opts.allowDiskUse)
  1745. ? args.pop()
  1746. : {};
  1747. // Left over arguments is the pipeline
  1748. pipeline = args;
  1749. }
  1750. const cursor = new AggregationCursor(
  1751. this.s.topology,
  1752. new AggregateOperation(this, pipeline, options),
  1753. options
  1754. );
  1755. // TODO: remove this when NODE-2074 is resolved
  1756. if (typeof callback === 'function') {
  1757. callback(null, cursor);
  1758. return;
  1759. }
  1760. return cursor;
  1761. };
  1762. /**
  1763. * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection.
  1764. * @method
  1765. * @since 3.0.0
  1766. * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/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.
  1767. * @param {object} [options] Optional settings
  1768. * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred.
  1769. * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document.
  1770. * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query
  1771. * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.
  1772. * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.
  1773. * @param {ReadPreference} [options.readPreference] The read preference. Defaults to the read preference of the database or collection. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}.
  1774. * @param {Timestamp} [options.startAtOperationTime] receive change events that occur after the specified timestamp
  1775. * @param {ClientSession} [options.session] optional session to use for this operation
  1776. * @return {ChangeStream} a ChangeStream instance.
  1777. */
  1778. Collection.prototype.watch = function(pipeline, options) {
  1779. pipeline = pipeline || [];
  1780. options = options || {};
  1781. // Allow optionally not specifying a pipeline
  1782. if (!Array.isArray(pipeline)) {
  1783. options = pipeline;
  1784. pipeline = [];
  1785. }
  1786. return new ChangeStream(this, pipeline, options);
  1787. };
  1788. /**
  1789. * The callback format for results
  1790. * @callback Collection~parallelCollectionScanCallback
  1791. * @param {MongoError} error An error instance representing the error during the execution.
  1792. * @param {Cursor[]} cursors A list of cursors returned allowing for parallel reading of collection.
  1793. */
  1794. /**
  1795. * Return N number of parallel cursors for a collection allowing parallel reading of entire collection. There are
  1796. * no ordering guarantees for returned results.
  1797. * @method
  1798. * @param {object} [options] Optional settings.
  1799. * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  1800. * @param {number} [options.batchSize=1000] Set the batchSize for the getMoreCommand when iterating over the query results.
  1801. * @param {number} [options.numCursors=1] The maximum number of parallel command cursors to return (the number of returned cursors will be in the range 1:numCursors)
  1802. * @param {boolean} [options.raw=false] Return all BSON documents as Raw Buffer documents.
  1803. * @param {Collection~parallelCollectionScanCallback} [callback] The command result callback
  1804. * @return {Promise} returns Promise if no callback passed
  1805. */
  1806. Collection.prototype.parallelCollectionScan = deprecate(function(options, callback) {
  1807. if (typeof options === 'function') (callback = options), (options = { numCursors: 1 });
  1808. // Set number of cursors to 1
  1809. options.numCursors = options.numCursors || 1;
  1810. options.batchSize = options.batchSize || 1000;
  1811. options = Object.assign({}, options);
  1812. // Ensure we have the right read preference inheritance
  1813. options.readPreference = ReadPreference.resolve(this, options);
  1814. // Add a promiseLibrary
  1815. options.promiseLibrary = this.s.promiseLibrary;
  1816. if (options.session) {
  1817. options.session = undefined;
  1818. }
  1819. return executeLegacyOperation(
  1820. this.s.topology,
  1821. parallelCollectionScan,
  1822. [this, options, callback],
  1823. { skipSessions: true }
  1824. );
  1825. }, 'parallelCollectionScan is deprecated in MongoDB v4.1');
  1826. /**
  1827. * Execute a geo search using a geo haystack index on a collection.
  1828. *
  1829. * @method
  1830. * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order.
  1831. * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order.
  1832. * @param {object} [options] Optional settings.
  1833. * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  1834. * @param {number} [options.maxDistance] Include results up to maxDistance from the point.
  1835. * @param {object} [options.search] Filter the results by a query.
  1836. * @param {number} [options.limit=false] Max number of results to return.
  1837. * @param {ClientSession} [options.session] optional session to use for this operation
  1838. * @param {Collection~resultCallback} [callback] The command result callback
  1839. * @return {Promise} returns Promise if no callback passed
  1840. * @deprecated See {@link https://docs.mongodb.com/manual/geospatial-queries/|geospatial queries docs} for current geospatial support
  1841. */
  1842. Collection.prototype.geoHaystackSearch = deprecate(function(x, y, options, callback) {
  1843. const args = Array.prototype.slice.call(arguments, 2);
  1844. callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
  1845. options = args.length ? args.shift() || {} : {};
  1846. const geoHaystackSearchOperation = new GeoHaystackSearchOperation(this, x, y, options);
  1847. return executeOperation(this.s.topology, geoHaystackSearchOperation, callback);
  1848. }, 'geoHaystackSearch is deprecated, and will be removed in a future version.');
  1849. /**
  1850. * Run a group command across a collection
  1851. *
  1852. * @method
  1853. * @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by.
  1854. * @param {object} condition An optional condition that must be true for a row to be considered.
  1855. * @param {object} initial Initial value of the aggregation counter object.
  1856. * @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated
  1857. * @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned.
  1858. * @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true.
  1859. * @param {object} [options] Optional settings.
  1860. * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  1861. * @param {ClientSession} [options.session] optional session to use for this operation
  1862. * @param {Collection~resultCallback} [callback] The command result callback
  1863. * @return {Promise} returns Promise if no callback passed
  1864. * @deprecated MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework.
  1865. */
  1866. Collection.prototype.group = deprecate(function(
  1867. keys,
  1868. condition,
  1869. initial,
  1870. reduce,
  1871. finalize,
  1872. command,
  1873. options,
  1874. callback
  1875. ) {
  1876. const args = Array.prototype.slice.call(arguments, 3);
  1877. callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
  1878. reduce = args.length ? args.shift() : null;
  1879. finalize = args.length ? args.shift() : null;
  1880. command = args.length ? args.shift() : null;
  1881. options = args.length ? args.shift() || {} : {};
  1882. // Make sure we are backward compatible
  1883. if (!(typeof finalize === 'function')) {
  1884. command = finalize;
  1885. finalize = null;
  1886. }
  1887. if (
  1888. !Array.isArray(keys) &&
  1889. keys instanceof Object &&
  1890. typeof keys !== 'function' &&
  1891. !(keys._bsontype === 'Code')
  1892. ) {
  1893. keys = Object.keys(keys);
  1894. }
  1895. if (typeof reduce === 'function') {
  1896. reduce = reduce.toString();
  1897. }
  1898. if (typeof finalize === 'function') {
  1899. finalize = finalize.toString();
  1900. }
  1901. // Set up the command as default
  1902. command = command == null ? true : command;
  1903. return executeLegacyOperation(this.s.topology, group, [
  1904. this,
  1905. keys,
  1906. condition,
  1907. initial,
  1908. reduce,
  1909. finalize,
  1910. command,
  1911. options,
  1912. callback
  1913. ]);
  1914. },
  1915. 'MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework.');
  1916. /**
  1917. * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection.
  1918. *
  1919. * @method
  1920. * @param {(function|string)} map The mapping function.
  1921. * @param {(function|string)} reduce The reduce function.
  1922. * @param {object} [options] Optional settings.
  1923. * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  1924. * @param {object} [options.out] Sets the output target for the map reduce job. *{inline:1} | {replace:'collectionName'} | {merge:'collectionName'} | {reduce:'collectionName'}*
  1925. * @param {object} [options.query] Query filter object.
  1926. * @param {object} [options.sort] Sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces.
  1927. * @param {number} [options.limit] Number of objects to return from collection.
  1928. * @param {boolean} [options.keeptemp=false] Keep temporary data.
  1929. * @param {(function|string)} [options.finalize] Finalize function.
  1930. * @param {object} [options.scope] Can pass in variables that can be access from map/reduce/finalize.
  1931. * @param {boolean} [options.jsMode=false] It is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X.
  1932. * @param {boolean} [options.verbose=false] Provide statistics on job execution time.
  1933. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  1934. * @param {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [options.explain] The verbosity mode for the explain output.
  1935. * @param {ClientSession} [options.session] optional session to use for this operation
  1936. * @param {Collection~resultCallback} [callback] The command result callback
  1937. * @throws {MongoError}
  1938. * @return {Promise} returns Promise if no callback passed
  1939. */
  1940. Collection.prototype.mapReduce = function(map, reduce, options, callback) {
  1941. if ('function' === typeof options) (callback = options), (options = {});
  1942. // Out must allways be defined (make sure we don't break weirdly on pre 1.8+ servers)
  1943. if (null == options.out) {
  1944. throw new Error(
  1945. 'the out option parameter must be defined, see mongodb docs for possible values'
  1946. );
  1947. }
  1948. if ('function' === typeof map) {
  1949. map = map.toString();
  1950. }
  1951. if ('function' === typeof reduce) {
  1952. reduce = reduce.toString();
  1953. }
  1954. if ('function' === typeof options.finalize) {
  1955. options.finalize = options.finalize.toString();
  1956. }
  1957. const mapReduceOperation = new MapReduceOperation(this, map, reduce, options);
  1958. return executeOperation(this.s.topology, mapReduceOperation, callback);
  1959. };
  1960. /**
  1961. * Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order.
  1962. *
  1963. * @method
  1964. * @param {object} [options] Optional settings.
  1965. * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead.
  1966. * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead.
  1967. * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead.
  1968. * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings.
  1969. * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
  1970. * @param {ClientSession} [options.session] optional session to use for this operation
  1971. * @return {UnorderedBulkOperation}
  1972. */
  1973. Collection.prototype.initializeUnorderedBulkOp = function(options) {
  1974. options = options || {};
  1975. // Give function's options precedence over session options.
  1976. if (options.ignoreUndefined == null) {
  1977. options.ignoreUndefined = this.s.options.ignoreUndefined;
  1978. }
  1979. options.promiseLibrary = this.s.promiseLibrary;
  1980. return unordered(this.s.topology, this, options);
  1981. };
  1982. /**
  1983. * 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.
  1984. *
  1985. * @method
  1986. * @param {object} [options] Optional settings.
  1987. * @param {(number|string)} [options.w] **Deprecated** The write concern. Use writeConcern instead.
  1988. * @param {number} [options.wtimeout] **Deprecated** The write concern timeout. Use writeConcern instead.
  1989. * @param {boolean} [options.j=false] **Deprecated** Specify a journal write concern. Use writeConcern instead.
  1990. * @param {object|WriteConcern} [options.writeConcern] Specify write concern settings.
  1991. * @param {ClientSession} [options.session] optional session to use for this operation
  1992. * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
  1993. * @return {null}
  1994. */
  1995. Collection.prototype.initializeOrderedBulkOp = function(options) {
  1996. options = options || {};
  1997. // Give function's options precedence over session's options.
  1998. if (options.ignoreUndefined == null) {
  1999. options.ignoreUndefined = this.s.options.ignoreUndefined;
  2000. }
  2001. options.promiseLibrary = this.s.promiseLibrary;
  2002. return ordered(this.s.topology, this, options);
  2003. };
  2004. /**
  2005. * Return the db logger
  2006. * @method
  2007. * @return {Logger} return the db logger
  2008. * @ignore
  2009. */
  2010. Collection.prototype.getLogger = function() {
  2011. return this.s.db.s.logger;
  2012. };
  2013. module.exports = Collection;