collection.js 112 KB

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