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