collection.js 96 KB

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