collection.js 105 KB

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