collection.js 92 KB

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