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
|
// expression_parser.cpp
/**
* Copyright (C) 2013 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/platform/basic.h"
#include "mongo/db/matcher/expression_parser.h"
#include <boost/container/flat_set.hpp>
#include <pcrecpp.h>
#include "mongo/base/init.h"
#include "mongo/bson/bsonmisc.h"
#include "mongo/bson/bsonobj.h"
#include "mongo/bson/bsonobjbuilder.h"
#include "mongo/db/matcher/expression_always_boolean.h"
#include "mongo/db/matcher/expression_array.h"
#include "mongo/db/matcher/expression_expr.h"
#include "mongo/db/matcher/expression_geo.h"
#include "mongo/db/matcher/expression_leaf.h"
#include "mongo/db/matcher/expression_tree.h"
#include "mongo/db/matcher/expression_type.h"
#include "mongo/db/matcher/expression_with_placeholder.h"
#include "mongo/db/matcher/schema/expression_internal_schema_all_elem_match_from_index.h"
#include "mongo/db/matcher/schema/expression_internal_schema_allowed_properties.h"
#include "mongo/db/matcher/schema/expression_internal_schema_cond.h"
#include "mongo/db/matcher/schema/expression_internal_schema_eq.h"
#include "mongo/db/matcher/schema/expression_internal_schema_fmod.h"
#include "mongo/db/matcher/schema/expression_internal_schema_match_array_index.h"
#include "mongo/db/matcher/schema/expression_internal_schema_max_items.h"
#include "mongo/db/matcher/schema/expression_internal_schema_max_length.h"
#include "mongo/db/matcher/schema/expression_internal_schema_max_properties.h"
#include "mongo/db/matcher/schema/expression_internal_schema_min_items.h"
#include "mongo/db/matcher/schema/expression_internal_schema_min_length.h"
#include "mongo/db/matcher/schema/expression_internal_schema_min_properties.h"
#include "mongo/db/matcher/schema/expression_internal_schema_object_match.h"
#include "mongo/db/matcher/schema/expression_internal_schema_root_doc_eq.h"
#include "mongo/db/matcher/schema/expression_internal_schema_unique_items.h"
#include "mongo/db/matcher/schema/expression_internal_schema_xor.h"
#include "mongo/db/matcher/schema/json_schema_parser.h"
#include "mongo/db/namespace_string.h"
#include "mongo/db/query/query_knobs.h"
#include "mongo/stdx/memory.h"
#include "mongo/util/mongoutils/str.h"
#include "mongo/util/string_map.h"
namespace {
using namespace mongo;
/**
* Returns true if subtree contains MatchExpression 'type'.
*/
bool hasNode(const MatchExpression* root, MatchExpression::MatchType type) {
if (type == root->matchType()) {
return true;
}
for (size_t i = 0; i < root->numChildren(); ++i) {
if (hasNode(root->getChild(i), type)) {
return true;
}
}
return false;
}
const boost::container::flat_set<StringData> topLevelOperators{"$_internalSchemaAllowedProperties",
"$_internalSchemaMaxProperties",
"$_internalSchemaMinProperties",
"$_internalSchemaXor",
"$and",
"$nor",
"$or",
"$where"};
} // namespace
namespace mongo {
constexpr StringData MatchExpressionParser::kAggExpression;
constexpr StringData AlwaysFalseMatchExpression::kName;
constexpr StringData AlwaysTrueMatchExpression::kName;
using std::string;
using stdx::make_unique;
const double MatchExpressionParser::kLongLongMaxPlusOneAsDouble =
scalbn(1, std::numeric_limits<long long>::digits);
StatusWithMatchExpression MatchExpressionParser::_parseComparison(
const char* name,
ComparisonMatchExpression* cmp,
const BSONElement& e,
const boost::intrusive_ptr<ExpressionContext>& expCtx,
AllowedFeatureSet allowedFeatures) {
std::unique_ptr<ComparisonMatchExpression> temp(cmp);
// Non-equality comparison match expressions cannot have
// a regular expression as the argument (e.g. {a: {$gt: /b/}} is illegal).
if (MatchExpression::EQ != cmp->matchType() && RegEx == e.type()) {
mongoutils::str::stream ss;
ss << "Can't have RegEx as arg to predicate over field '" << name << "'.";
return {Status(ErrorCodes::BadValue, ss)};
}
auto s = temp->init(name, e);
if (!s.isOK()) {
return s;
}
temp->setCollator(expCtx->getCollator());
return {std::move(temp)};
}
StatusWithMatchExpression MatchExpressionParser::_parseSubField(
const BSONObj& context,
const AndMatchExpression* andSoFar,
const char* name,
const BSONElement& e,
const boost::intrusive_ptr<ExpressionContext>& expCtx,
AllowedFeatureSet allowedFeatures,
bool topLevel) {
if (mongoutils::str::equals("$eq", e.fieldName()))
return _parseComparison(name, new EqualityMatchExpression(), e, expCtx, allowedFeatures);
if (mongoutils::str::equals("$not", e.fieldName())) {
return _parseNot(name, e, expCtx, allowedFeatures, topLevel);
}
auto parseExpMatchType = MatchExpressionParser::parsePathAcceptingKeyword(e);
if (!parseExpMatchType) {
// $where cannot be a sub-expression because it works on top-level documents only.
if (mongoutils::str::equals("$where", e.fieldName())) {
return {Status(ErrorCodes::BadValue, "$where cannot be applied to a field")};
}
return {Status(ErrorCodes::BadValue,
mongoutils::str::stream() << "unknown operator: " << e.fieldName())};
}
switch (*parseExpMatchType) {
case PathAcceptingKeyword::LESS_THAN:
return _parseComparison(name, new LTMatchExpression(), e, expCtx, allowedFeatures);
case PathAcceptingKeyword::LESS_THAN_OR_EQUAL:
return _parseComparison(name, new LTEMatchExpression(), e, expCtx, allowedFeatures);
case PathAcceptingKeyword::GREATER_THAN:
return _parseComparison(name, new GTMatchExpression(), e, expCtx, allowedFeatures);
case PathAcceptingKeyword::GREATER_THAN_OR_EQUAL:
return _parseComparison(name, new GTEMatchExpression(), e, expCtx, allowedFeatures);
case PathAcceptingKeyword::NOT_EQUAL: {
if (RegEx == e.type()) {
// Just because $ne can be rewritten as the negation of an
// equality does not mean that $ne of a regex is allowed. See SERVER-1705.
return {Status(ErrorCodes::BadValue, "Can't have regex as arg to $ne.")};
}
StatusWithMatchExpression s =
_parseComparison(name, new EqualityMatchExpression(), e, expCtx, allowedFeatures);
if (!s.isOK())
return s;
std::unique_ptr<NotMatchExpression> n = stdx::make_unique<NotMatchExpression>();
Status s2 = n->init(s.getValue().release());
if (!s2.isOK())
return s2;
return {std::move(n)};
}
case PathAcceptingKeyword::EQUALITY:
return _parseComparison(
name, new EqualityMatchExpression(), e, expCtx, allowedFeatures);
case PathAcceptingKeyword::IN_EXPR: {
if (e.type() != Array)
return {Status(ErrorCodes::BadValue, "$in needs an array")};
std::unique_ptr<InMatchExpression> temp = stdx::make_unique<InMatchExpression>();
Status s = temp->init(name);
if (!s.isOK())
return s;
s = _parseInExpression(temp.get(), e.Obj(), expCtx);
if (!s.isOK())
return s;
return {std::move(temp)};
}
case PathAcceptingKeyword::NOT_IN: {
if (e.type() != Array)
return {Status(ErrorCodes::BadValue, "$nin needs an array")};
std::unique_ptr<InMatchExpression> temp = stdx::make_unique<InMatchExpression>();
Status s = temp->init(name);
if (!s.isOK())
return s;
s = _parseInExpression(temp.get(), e.Obj(), expCtx);
if (!s.isOK())
return s;
std::unique_ptr<NotMatchExpression> temp2 = stdx::make_unique<NotMatchExpression>();
s = temp2->init(temp.release());
if (!s.isOK())
return s;
return {std::move(temp2)};
}
case PathAcceptingKeyword::SIZE: {
int size = 0;
if (e.type() == NumberInt) {
size = e.numberInt();
} else if (e.type() == NumberLong) {
if (e.numberInt() == e.numberLong()) {
size = e.numberInt();
} else {
return {Status(ErrorCodes::BadValue,
"$size must be representable as a 32-bit integer")};
}
} else if (e.type() == NumberDouble) {
if (e.numberInt() == e.numberDouble()) {
size = e.numberInt();
} else {
return {Status(ErrorCodes::BadValue, "$size must be a whole number")};
}
} else {
return {Status(ErrorCodes::BadValue, "$size needs a number")};
}
if (size < 0) {
return {Status(ErrorCodes::BadValue, "$size may not be negative")};
}
std::unique_ptr<SizeMatchExpression> temp = stdx::make_unique<SizeMatchExpression>();
Status s = temp->init(name, size);
if (!s.isOK())
return s;
return {std::move(temp)};
}
case PathAcceptingKeyword::EXISTS: {
if (e.eoo())
return {Status(ErrorCodes::BadValue, "$exists can't be eoo")};
std::unique_ptr<ExistsMatchExpression> temp =
stdx::make_unique<ExistsMatchExpression>();
Status s = temp->init(name);
if (!s.isOK())
return s;
if (e.trueValue())
return {std::move(temp)};
std::unique_ptr<NotMatchExpression> temp2 = stdx::make_unique<NotMatchExpression>();
s = temp2->init(temp.release());
if (!s.isOK())
return s;
return {std::move(temp2)};
}
case PathAcceptingKeyword::TYPE:
return _parseType<TypeMatchExpression>(name, e);
case PathAcceptingKeyword::MOD:
return _parseMOD(name, e);
case PathAcceptingKeyword::OPTIONS: {
// TODO: try to optimize this
// we have to do this since $options can be before or after a $regex
// but we validate here
BSONObjIterator i(context);
while (i.more()) {
BSONElement temp = i.next();
if (MatchExpressionParser::parsePathAcceptingKeyword(temp) ==
PathAcceptingKeyword::REGEX)
return {nullptr};
}
return {Status(ErrorCodes::BadValue, "$options needs a $regex")};
}
case PathAcceptingKeyword::REGEX: {
return _parseRegexDocument(name, context);
}
case PathAcceptingKeyword::ELEM_MATCH:
return _parseElemMatch(name, e, expCtx, allowedFeatures, topLevel);
case PathAcceptingKeyword::ALL:
return _parseAll(name, e, expCtx, allowedFeatures, topLevel);
case PathAcceptingKeyword::WITHIN:
case PathAcceptingKeyword::GEO_INTERSECTS:
return _parseGeo(name, *parseExpMatchType, context, allowedFeatures);
case PathAcceptingKeyword::GEO_NEAR:
return {Status(ErrorCodes::BadValue,
mongoutils::str::stream() << "near must be first in: " << context)};
// Handles bitwise query operators.
case PathAcceptingKeyword::BITS_ALL_SET: {
return _parseBitTest<BitsAllSetMatchExpression>(name, e);
}
case PathAcceptingKeyword::BITS_ALL_CLEAR: {
return _parseBitTest<BitsAllClearMatchExpression>(name, e);
}
case PathAcceptingKeyword::BITS_ANY_SET: {
return _parseBitTest<BitsAnySetMatchExpression>(name, e);
}
case PathAcceptingKeyword::BITS_ANY_CLEAR: {
return _parseBitTest<BitsAnyClearMatchExpression>(name, e);
}
case PathAcceptingKeyword::INTERNAL_SCHEMA_FMOD:
return _parseInternalSchemaFmod(name, e);
case PathAcceptingKeyword::INTERNAL_SCHEMA_MIN_ITEMS: {
return _parseInternalSchemaSingleIntegerArgument<InternalSchemaMinItemsMatchExpression>(
name, e);
}
case PathAcceptingKeyword::INTERNAL_SCHEMA_MAX_ITEMS: {
return _parseInternalSchemaSingleIntegerArgument<InternalSchemaMaxItemsMatchExpression>(
name, e);
}
case PathAcceptingKeyword::INTERNAL_SCHEMA_OBJECT_MATCH: {
if (e.type() != BSONType::Object) {
return Status(ErrorCodes::FailedToParse,
str::stream() << "$_internalSchemaObjectMatch must be an object");
}
auto parsedSubObjExpr = _parse(e.Obj(), expCtx, allowedFeatures, topLevel);
if (!parsedSubObjExpr.isOK()) {
return parsedSubObjExpr;
}
auto expr = stdx::make_unique<InternalSchemaObjectMatchExpression>();
auto status = expr->init(std::move(parsedSubObjExpr.getValue()), name);
if (!status.isOK()) {
return status;
}
return {std::move(expr)};
}
case PathAcceptingKeyword::INTERNAL_SCHEMA_UNIQUE_ITEMS: {
if (!e.isBoolean() || !e.boolean()) {
return {ErrorCodes::FailedToParse,
str::stream() << name << " must be a boolean of value true"};
}
auto expr = stdx::make_unique<InternalSchemaUniqueItemsMatchExpression>();
auto status = expr->init(name);
if (!status.isOK()) {
return status;
}
return {std::move(expr)};
}
case PathAcceptingKeyword::INTERNAL_SCHEMA_MIN_LENGTH: {
return _parseInternalSchemaSingleIntegerArgument<
InternalSchemaMinLengthMatchExpression>(name, e);
}
case PathAcceptingKeyword::INTERNAL_SCHEMA_MAX_LENGTH: {
return _parseInternalSchemaSingleIntegerArgument<
InternalSchemaMaxLengthMatchExpression>(name, e);
}
case PathAcceptingKeyword::INTERNAL_SCHEMA_MATCH_ARRAY_INDEX: {
return _parseInternalSchemaMatchArrayIndex(name, e, expCtx);
}
case PathAcceptingKeyword::INTERNAL_SCHEMA_ALL_ELEM_MATCH_FROM_INDEX: {
if (e.type() != BSONType::Array) {
return Status(ErrorCodes::FailedToParse,
str::stream()
<< InternalSchemaAllElemMatchFromIndexMatchExpression::kName
<< " must be an array");
}
auto elemMatchObj = e.embeddedObject();
auto iter = elemMatchObj.begin();
if (!iter.more()) {
return Status(ErrorCodes::FailedToParse,
str::stream()
<< InternalSchemaAllElemMatchFromIndexMatchExpression::kName
<< " must be an array of size 2");
}
auto first = iter.next();
auto parsedIndex = parseIntegerElementToNonNegativeLong(first);
if (!parsedIndex.isOK()) {
return Status(ErrorCodes::TypeMismatch,
str::stream()
<< "first element of "
<< InternalSchemaAllElemMatchFromIndexMatchExpression::kName
<< " must be a non-negative integer");
}
if (!iter.more()) {
return Status(ErrorCodes::FailedToParse,
str::stream()
<< InternalSchemaAllElemMatchFromIndexMatchExpression::kName
<< " must be an array of size 2");
}
auto second = iter.next();
if (iter.more()) {
return Status(ErrorCodes::FailedToParse,
str::stream()
<< InternalSchemaAllElemMatchFromIndexMatchExpression::kName
<< " has too many elements, must be an array of size 2");
}
if (second.type() != BSONType::Object) {
return Status(ErrorCodes::TypeMismatch,
str::stream()
<< "second element of "
<< InternalSchemaAllElemMatchFromIndexMatchExpression::kName
<< "must be an object");
}
auto exprWithPlaceholder =
ExpressionWithPlaceholder::parse(second.embeddedObject(), expCtx);
if (!exprWithPlaceholder.isOK()) {
return exprWithPlaceholder.getStatus();
}
auto expr = stdx::make_unique<InternalSchemaAllElemMatchFromIndexMatchExpression>();
auto status =
expr->init(name, parsedIndex.getValue(), std::move(exprWithPlaceholder.getValue()));
if (!status.isOK()) {
return status;
}
return {std::move(expr)};
}
case PathAcceptingKeyword::INTERNAL_SCHEMA_TYPE: {
return _parseType<InternalSchemaTypeExpression>(name, e);
}
case PathAcceptingKeyword::INTERNAL_SCHEMA_EQ: {
auto eqExpr = stdx::make_unique<InternalSchemaEqMatchExpression>();
auto status = eqExpr->init(name, e);
if (!status.isOK()) {
return status;
}
return {std::move(eqExpr)};
}
}
return {Status(ErrorCodes::BadValue,
mongoutils::str::stream() << "not handled: " << e.fieldName())};
}
StatusWithMatchExpression MatchExpressionParser::_parse(
const BSONObj& obj,
const boost::intrusive_ptr<ExpressionContext>& expCtx,
AllowedFeatureSet allowedFeatures,
bool topLevel) {
std::unique_ptr<AndMatchExpression> root = stdx::make_unique<AndMatchExpression>();
const bool childIsTopLevel = false;
BSONObjIterator i(obj);
while (i.more()) {
BSONElement e = i.next();
if (e.fieldName()[0] == '$') {
const char* rest = e.fieldName() + 1;
if (mongoutils::str::equals("or", rest)) {
if (e.type() != Array)
return {Status(ErrorCodes::BadValue, "$or must be an array")};
std::unique_ptr<OrMatchExpression> temp = stdx::make_unique<OrMatchExpression>();
Status s =
_parseTreeList(e.Obj(), temp.get(), expCtx, allowedFeatures, childIsTopLevel);
if (!s.isOK())
return s;
root->add(temp.release());
} else if (mongoutils::str::equals("and", rest)) {
if (e.type() != Array)
return {Status(ErrorCodes::BadValue, "$and must be an array")};
std::unique_ptr<AndMatchExpression> temp = stdx::make_unique<AndMatchExpression>();
Status s =
_parseTreeList(e.Obj(), temp.get(), expCtx, allowedFeatures, childIsTopLevel);
if (!s.isOK())
return s;
root->add(temp.release());
} else if (mongoutils::str::equals("nor", rest)) {
if (e.type() != Array)
return {Status(ErrorCodes::BadValue, "$nor must be an array")};
std::unique_ptr<NorMatchExpression> temp = stdx::make_unique<NorMatchExpression>();
Status s =
_parseTreeList(e.Obj(), temp.get(), expCtx, allowedFeatures, childIsTopLevel);
if (!s.isOK())
return s;
root->add(temp.release());
} else if (mongoutils::str::equals("atomic", rest) ||
mongoutils::str::equals("isolated", rest)) {
if (!topLevel)
return {Status(ErrorCodes::BadValue,
"$atomic/$isolated has to be at the top level")};
// Don't do anything with the expression; CanonicalQuery::init() will look through
// the BSONObj again for a $atomic/$isolated.
} else if (mongoutils::str::equals("where", rest)) {
if ((allowedFeatures & AllowedFeatures::kJavascript) == 0u) {
return {Status(ErrorCodes::BadValue, "$where is not allowed in this context")};
}
StatusWithMatchExpression s = _extensionsCallback->parseWhere(e);
if (!s.isOK())
return s;
root->add(s.getValue().release());
} else if (mongoutils::str::equals("expr", rest)) {
if (!topLevel) {
return {Status(ErrorCodes::BadValue, "$expr has to be at the top level")};
}
auto status = _parseExpr(e, allowedFeatures, expCtx);
if (!status.isOK())
return status;
root->add(status.getValue().release());
} else if (mongoutils::str::equals("text", rest)) {
if ((allowedFeatures & AllowedFeatures::kText) == 0u) {
return {Status(ErrorCodes::BadValue, "$text is not allowed in this context")};
}
StatusWithMatchExpression s = _extensionsCallback->parseText(e);
if (!s.isOK()) {
return s;
}
root->add(s.getValue().release());
} else if (mongoutils::str::equals("comment", rest)) {
} else if (mongoutils::str::equals("ref", rest) ||
mongoutils::str::equals("id", rest) || mongoutils::str::equals("db", rest)) {
// DBRef fields.
std::unique_ptr<ComparisonMatchExpression> eq =
stdx::make_unique<EqualityMatchExpression>();
Status s = eq->init(e.fieldName(), e);
if (!s.isOK())
return s;
// 'id' is collation-aware. 'ref' and 'db' are compared using binary comparison.
eq->setCollator(str::equals("id", rest) ? expCtx->getCollator() : nullptr);
root->add(eq.release());
} else if (mongoutils::str::equals("_internalSchemaAllowedProperties", rest)) {
auto allowedProperties = _parseInternalSchemaAllowedProperties(e, expCtx);
if (!allowedProperties.isOK()) {
return allowedProperties.getStatus();
}
root->add(allowedProperties.getValue().release());
} else if (mongoutils::str::equals("_internalSchemaCond", rest)) {
auto condExpr =
_parseInternalSchemaFixedArityArgument<InternalSchemaCondMatchExpression>(
InternalSchemaCondMatchExpression::kName, e, expCtx, allowedFeatures);
if (!condExpr.isOK()) {
return condExpr.getStatus();
}
root->add(condExpr.getValue().release());
} else if (mongoutils::str::equals("_internalSchemaXor", rest)) {
if (e.type() != BSONType::Array)
return {
Status(ErrorCodes::TypeMismatch, "$_internalSchemaXor must be an array")};
auto xorExpr = stdx::make_unique<InternalSchemaXorMatchExpression>();
Status s = _parseTreeList(
e.Obj(), xorExpr.get(), expCtx, allowedFeatures, childIsTopLevel);
if (!s.isOK())
return s;
root->add(xorExpr.release());
} else if (mongoutils::str::equals("_internalSchemaMinProperties", rest)) {
auto minPropsExpr = _parseTopLevelInternalSchemaSingleIntegerArgument<
InternalSchemaMinPropertiesMatchExpression>(e);
if (!minPropsExpr.isOK()) {
return minPropsExpr.getStatus();
}
root->add(minPropsExpr.getValue().release());
} else if (mongoutils::str::equals("_internalSchemaMaxProperties", rest)) {
auto maxPropsExpr = _parseTopLevelInternalSchemaSingleIntegerArgument<
InternalSchemaMaxPropertiesMatchExpression>(e);
if (!maxPropsExpr.isOK()) {
return maxPropsExpr.getStatus();
}
root->add(maxPropsExpr.getValue().release());
} else if (mongoutils::str::equals("jsonSchema", rest)) {
if ((allowedFeatures & AllowedFeatures::kJSONSchema) == 0u) {
return Status(ErrorCodes::JSONSchemaNotAllowed,
"$jsonSchema is not allowed in this context");
}
if (e.type() != BSONType::Object) {
return {Status(ErrorCodes::TypeMismatch, "$jsonSchema must be an object")};
}
auto schemaMatch = JSONSchemaParser::parse(
e.Obj(), internalQueryIgnoreUnknownJSONSchemaKeywords.load());
if (!schemaMatch.isOK()) {
return schemaMatch.getStatus();
}
root->add(schemaMatch.getValue().release());
} else if (mongoutils::str::equals("alwaysFalse", rest)) {
auto statusWithLong = MatchExpressionParser::parseIntegerElementToLong(e);
if (!statusWithLong.isOK()) {
return statusWithLong.getStatus();
}
if (statusWithLong.getValue() != 1) {
return {Status(ErrorCodes::FailedToParse,
"$alwaysFalse must be an integer value of 1")};
}
auto alwaysFalseExpr = stdx::make_unique<AlwaysFalseMatchExpression>();
root->add(alwaysFalseExpr.release());
} else if (mongoutils::str::equals("alwaysTrue", rest)) {
auto statusWithLong = MatchExpressionParser::parseIntegerElementToLong(e);
if (!statusWithLong.isOK()) {
return statusWithLong.getStatus();
}
if (statusWithLong.getValue() != 1) {
return {Status(ErrorCodes::FailedToParse,
"$alwaysTrue must be an integer value of 1")};
}
auto alwaysTrueExpr = stdx::make_unique<AlwaysTrueMatchExpression>();
root->add(alwaysTrueExpr.release());
} else if (mongoutils::str::equals("_internalSchemaRootDocEq", rest)) {
if (!topLevel) {
return {Status(ErrorCodes::FailedToParse,
str::stream() << InternalSchemaRootDocEqMatchExpression::kName
<< " must be at the top level")};
}
if (e.type() != BSONType::Object) {
return {Status(ErrorCodes::TypeMismatch,
str::stream() << InternalSchemaRootDocEqMatchExpression::kName
<< " must be an object, found type "
<< e.type())};
}
auto rootDocEq = stdx::make_unique<InternalSchemaRootDocEqMatchExpression>();
rootDocEq->init(e.embeddedObject());
root->add(rootDocEq.release());
} else {
return {Status(ErrorCodes::BadValue,
mongoutils::str::stream() << "unknown top level operator: "
<< e.fieldName())};
}
continue;
}
if (_isExpressionDocument(e, false)) {
Status s = _parseSub(
e.fieldName(), e.Obj(), root.get(), expCtx, allowedFeatures, childIsTopLevel);
if (!s.isOK())
return s;
continue;
}
if (e.type() == RegEx) {
StatusWithMatchExpression result = _parseRegexElement(e.fieldName(), e);
if (!result.isOK())
return result;
root->add(result.getValue().release());
continue;
}
auto eq = _parseComparison(
e.fieldName(), new EqualityMatchExpression(), e, expCtx, allowedFeatures);
if (!eq.isOK())
return eq;
root->add(eq.getValue().release());
}
if (root->numChildren() == 1) {
std::unique_ptr<MatchExpression> real(root->getChild(0));
root->clearAndRelease();
return {std::move(real)};
}
return {std::move(root)};
}
Status MatchExpressionParser::_parseSub(const char* name,
const BSONObj& sub,
AndMatchExpression* root,
const boost::intrusive_ptr<ExpressionContext>& expCtx,
AllowedFeatureSet allowedFeatures,
bool topLevel) {
// The one exception to {field : {fully contained argument} } is, of course, geo. Example:
// sub == { field : {$near[Sphere]: [0,0], $maxDistance: 1000, $minDistance: 10 } }
// We peek inside of 'sub' to see if it's possibly a $near. If so, we can't iterate over
// its subfields and parse them one at a time (there is no $maxDistance without $near), so
// we hand the entire object over to the geo parsing routines.
// Special case parsing for geoNear. This is necessary in order to support query formats like
// {$near: <coords>, $maxDistance: <distance>}. No other query operators allow $-prefixed
// modifiers as sibling BSON elements.
BSONObjIterator geoIt(sub);
if (geoIt.more()) {
BSONElement firstElt = geoIt.next();
if (firstElt.isABSONObj()) {
if (MatchExpressionParser::parsePathAcceptingKeyword(firstElt) ==
PathAcceptingKeyword::GEO_NEAR) {
StatusWithMatchExpression s =
_parseGeo(name, PathAcceptingKeyword::GEO_NEAR, sub, allowedFeatures);
if (s.isOK()) {
root->add(s.getValue().release());
}
// Propagate geo parsing result to caller.
return s.getStatus();
}
}
}
BSONObjIterator j(sub);
while (j.more()) {
BSONElement deep = j.next();
const bool childIsTopLevel = false;
StatusWithMatchExpression s =
_parseSubField(sub, root, name, deep, expCtx, allowedFeatures, childIsTopLevel);
if (!s.isOK())
return s.getStatus();
if (s.getValue())
root->add(s.getValue().release());
}
return Status::OK();
}
bool MatchExpressionParser::_isExpressionDocument(const BSONElement& e, bool allowIncompleteDBRef) {
if (e.type() != Object)
return false;
BSONObj o = e.Obj();
if (o.isEmpty())
return false;
const char* name = o.firstElement().fieldName();
if (name[0] != '$')
return false;
if (_isDBRefDocument(o, allowIncompleteDBRef)) {
return false;
}
return true;
}
/**
* DBRef fields are ordered in the collection.
* In the query, we consider an embedded object a query on
* a DBRef as long as it contains $ref and $id.
* Required fields: $ref and $id (if incomplete DBRefs are not allowed)
*
* If incomplete DBRefs are allowed, we accept the BSON object as long as it
* contains $ref, $id or $db.
*
* Field names are checked but not field types.
*/
bool MatchExpressionParser::_isDBRefDocument(const BSONObj& obj, bool allowIncompleteDBRef) {
bool hasRef = false;
bool hasID = false;
bool hasDB = false;
BSONObjIterator i(obj);
while (i.more() && !(hasRef && hasID)) {
BSONElement element = i.next();
const char* fieldName = element.fieldName();
// $ref
if (!hasRef && mongoutils::str::equals("$ref", fieldName)) {
hasRef = true;
}
// $id
else if (!hasID && mongoutils::str::equals("$id", fieldName)) {
hasID = true;
}
// $db
else if (!hasDB && mongoutils::str::equals("$db", fieldName)) {
hasDB = true;
}
}
if (allowIncompleteDBRef) {
return hasRef || hasID || hasDB;
}
return hasRef && hasID;
}
StatusWithMatchExpression MatchExpressionParser::_parseMOD(const char* name, const BSONElement& e) {
if (e.type() != Array)
return {Status(ErrorCodes::BadValue, "malformed mod, needs to be an array")};
BSONObjIterator i(e.Obj());
if (!i.more())
return {Status(ErrorCodes::BadValue, "malformed mod, not enough elements")};
BSONElement d = i.next();
if (!d.isNumber())
return {Status(ErrorCodes::BadValue, "malformed mod, divisor not a number")};
if (!i.more())
return {Status(ErrorCodes::BadValue, "malformed mod, not enough elements")};
BSONElement r = i.next();
if (!d.isNumber())
return {Status(ErrorCodes::BadValue, "malformed mod, remainder not a number")};
if (i.more())
return {Status(ErrorCodes::BadValue, "malformed mod, too many elements")};
std::unique_ptr<ModMatchExpression> temp = stdx::make_unique<ModMatchExpression>();
Status s = temp->init(name, d.numberInt(), r.numberInt());
if (!s.isOK())
return s;
return {std::move(temp)};
}
StatusWithMatchExpression MatchExpressionParser::_parseRegexElement(const char* name,
const BSONElement& e) {
if (e.type() != RegEx)
return {Status(ErrorCodes::BadValue, "not a regex")};
std::unique_ptr<RegexMatchExpression> temp = stdx::make_unique<RegexMatchExpression>();
Status s = temp->init(name, e.regex(), e.regexFlags());
if (!s.isOK())
return s;
return {std::move(temp)};
}
StatusWithMatchExpression MatchExpressionParser::_parseRegexDocument(const char* name,
const BSONObj& doc) {
string regex;
string regexOptions;
BSONObjIterator i(doc);
while (i.more()) {
BSONElement e = i.next();
auto matchType = MatchExpressionParser::parsePathAcceptingKeyword(e);
if (!matchType) {
continue;
}
switch (*matchType) {
case PathAcceptingKeyword::REGEX:
if (e.type() == String) {
regex = e.String();
} else if (e.type() == RegEx) {
regex = e.regex();
regexOptions = e.regexFlags();
} else {
return {Status(ErrorCodes::BadValue, "$regex has to be a string")};
}
break;
case PathAcceptingKeyword::OPTIONS:
if (e.type() != String)
return {Status(ErrorCodes::BadValue, "$options has to be a string")};
regexOptions = e.String();
break;
default:
break;
}
}
std::unique_ptr<RegexMatchExpression> temp = stdx::make_unique<RegexMatchExpression>();
Status s = temp->init(name, regex, regexOptions);
if (!s.isOK())
return s;
return {std::move(temp)};
}
Status MatchExpressionParser::_parseInExpression(
InMatchExpression* inExpression,
const BSONObj& theArray,
const boost::intrusive_ptr<ExpressionContext>& expCtx) {
inExpression->setCollator(expCtx->getCollator());
std::vector<BSONElement> equalities;
BSONObjIterator i(theArray);
while (i.more()) {
BSONElement e = i.next();
// Allow DBRefs, but reject all fields with names starting with $.
if (_isExpressionDocument(e, false)) {
return Status(ErrorCodes::BadValue, "cannot nest $ under $in");
}
if (e.type() == RegEx) {
std::unique_ptr<RegexMatchExpression> r = stdx::make_unique<RegexMatchExpression>();
Status s = r->init("", e);
if (!s.isOK())
return s;
s = inExpression->addRegex(std::move(r));
if (!s.isOK())
return s;
} else {
equalities.push_back(e);
}
}
return inExpression->setEqualities(std::move(equalities));
}
template <class T>
StatusWithMatchExpression MatchExpressionParser::_parseType(const char* name,
const BSONElement& elt) {
auto typeSet = MatcherTypeSet::parse(elt, MatcherTypeSet::kTypeAliasMap);
if (!typeSet.isOK()) {
return typeSet.getStatus();
}
auto typeExpr = stdx::make_unique<T>();
if (typeSet.getValue().isEmpty()) {
return {Status(ErrorCodes::FailedToParse,
str::stream() << typeExpr->name() << " must match at least one type")};
}
auto status = typeExpr->init(name, std::move(typeSet.getValue()));
if (!status.isOK()) {
return status;
}
return {std::move(typeExpr)};
}
StatusWithMatchExpression MatchExpressionParser::_parseElemMatch(
const char* name,
const BSONElement& e,
const boost::intrusive_ptr<ExpressionContext>& expCtx,
AllowedFeatureSet allowedFeatures,
bool topLevel) {
if (e.type() != Object)
return {Status(ErrorCodes::BadValue, "$elemMatch needs an Object")};
BSONObj obj = e.Obj();
// $elemMatch value case applies when the children all
// work on the field 'name'.
// This is the case when:
// 1) the argument is an expression document; and
// 2) expression is not a AND/NOR/OR logical operator. Children of
// these logical operators are initialized with field names.
// 3) expression is not a WHERE operator. WHERE works on objects instead
// of specific field.
bool isElemMatchValue = false;
if (_isExpressionDocument(e, true)) {
BSONObj o = e.Obj();
BSONElement elt = o.firstElement();
invariant(!elt.eoo());
isElemMatchValue =
topLevelOperators.find(elt.fieldNameStringData()) == topLevelOperators.end();
}
if (isElemMatchValue) {
// value case
AndMatchExpression theAnd;
Status s = _parseSub("", obj, &theAnd, expCtx, allowedFeatures, topLevel);
if (!s.isOK())
return s;
std::unique_ptr<ElemMatchValueMatchExpression> temp =
stdx::make_unique<ElemMatchValueMatchExpression>();
s = temp->init(name);
if (!s.isOK())
return s;
for (size_t i = 0; i < theAnd.numChildren(); i++) {
temp->add(theAnd.getChild(i));
}
theAnd.clearAndRelease();
return {std::move(temp)};
}
// DBRef value case
// A DBRef document under a $elemMatch should be treated as an object case
// because it may contain non-DBRef fields in addition to $ref, $id and $db.
// object case
StatusWithMatchExpression subRaw = _parse(obj, expCtx, allowedFeatures, topLevel);
if (!subRaw.isOK())
return subRaw;
std::unique_ptr<MatchExpression> sub = std::move(subRaw.getValue());
// $where is not supported under $elemMatch because $where
// applies to top-level document, not array elements in a field.
if (hasNode(sub.get(), MatchExpression::WHERE)) {
return {Status(ErrorCodes::BadValue, "$elemMatch cannot contain $where expression")};
}
std::unique_ptr<ElemMatchObjectMatchExpression> temp =
stdx::make_unique<ElemMatchObjectMatchExpression>();
Status status = temp->init(name, sub.release());
if (!status.isOK())
return status;
return {std::move(temp)};
}
StatusWithMatchExpression MatchExpressionParser::_parseAll(
const char* name,
const BSONElement& e,
const boost::intrusive_ptr<ExpressionContext>& expCtx,
AllowedFeatureSet allowedFeatures,
bool topLevel) {
if (e.type() != Array)
return {Status(ErrorCodes::BadValue, "$all needs an array")};
BSONObj arr = e.Obj();
std::unique_ptr<AndMatchExpression> myAnd = stdx::make_unique<AndMatchExpression>();
BSONObjIterator i(arr);
if (arr.firstElement().type() == Object &&
mongoutils::str::equals("$elemMatch",
arr.firstElement().Obj().firstElement().fieldName())) {
// $all : [ { $elemMatch : {} } ... ]
while (i.more()) {
BSONElement hopefullyElemMatchElement = i.next();
if (hopefullyElemMatchElement.type() != Object) {
// $all : [ { $elemMatch : ... }, 5 ]
return {Status(ErrorCodes::BadValue, "$all/$elemMatch has to be consistent")};
}
BSONObj hopefullyElemMatchObj = hopefullyElemMatchElement.Obj();
if (!mongoutils::str::equals("$elemMatch",
hopefullyElemMatchObj.firstElement().fieldName())) {
// $all : [ { $elemMatch : ... }, { x : 5 } ]
return {Status(ErrorCodes::BadValue, "$all/$elemMatch has to be consistent")};
}
const bool childIsTopLevel = false;
StatusWithMatchExpression inner = _parseElemMatch(name,
hopefullyElemMatchObj.firstElement(),
expCtx,
allowedFeatures,
childIsTopLevel);
if (!inner.isOK())
return inner;
myAnd->add(inner.getValue().release());
}
return {std::move(myAnd)};
}
while (i.more()) {
BSONElement e = i.next();
if (e.type() == RegEx) {
std::unique_ptr<RegexMatchExpression> r = stdx::make_unique<RegexMatchExpression>();
Status s = r->init(name, e);
if (!s.isOK())
return s;
myAnd->add(r.release());
} else if (e.type() == Object &&
MatchExpressionParser::parsePathAcceptingKeyword(e.Obj().firstElement())) {
return {Status(ErrorCodes::BadValue, "no $ expressions in $all")};
} else {
std::unique_ptr<EqualityMatchExpression> x =
stdx::make_unique<EqualityMatchExpression>();
Status s = x->init(name, e);
if (!s.isOK())
return s;
x->setCollator(expCtx->getCollator());
myAnd->add(x.release());
}
}
if (myAnd->numChildren() == 0) {
return {stdx::make_unique<AlwaysFalseMatchExpression>()};
}
return {std::move(myAnd)};
}
template <class T>
StatusWithMatchExpression MatchExpressionParser::_parseBitTest(const char* name,
const BSONElement& e) {
std::unique_ptr<BitTestMatchExpression> bitTestMatchExpression = stdx::make_unique<T>();
if (e.type() == BSONType::Array) {
// Array of bit positions provided as value.
auto statusWithBitPositions = _parseBitPositionsArray(e.Obj());
if (!statusWithBitPositions.isOK()) {
return statusWithBitPositions.getStatus();
}
std::vector<uint32_t> bitPositions = statusWithBitPositions.getValue();
Status s = bitTestMatchExpression->init(name, bitPositions);
if (!s.isOK()) {
return s;
}
} else if (e.isNumber()) {
// Integer bitmask provided as value.
auto bitMask = parseIntegerElementToNonNegativeLong(e);
if (!bitMask.isOK()) {
return bitMask.getStatus();
}
Status s = bitTestMatchExpression->init(name, bitMask.getValue());
if (!s.isOK()) {
return s;
}
} else if (e.type() == BSONType::BinData) {
// Binary bitmask provided as value.
int eBinaryLen;
const char* eBinary = e.binData(eBinaryLen);
Status s = bitTestMatchExpression->init(name, eBinary, eBinaryLen);
if (!s.isOK()) {
return s;
}
} else {
mongoutils::str::stream ss;
ss << name << " takes an Array, a number, or a BinData but received: " << e;
return Status(ErrorCodes::BadValue, ss);
}
return {std::move(bitTestMatchExpression)};
}
StatusWith<std::vector<uint32_t>> MatchExpressionParser::_parseBitPositionsArray(
const BSONObj& theArray) {
std::vector<uint32_t> bitPositions;
// Fill temporary bit position array with integers read from the BSON array.
for (const BSONElement& e : theArray) {
if (!e.isNumber()) {
mongoutils::str::stream ss;
ss << "bit positions must be an integer but got: " << e;
return Status(ErrorCodes::BadValue, ss);
}
if (e.type() == BSONType::NumberDouble) {
double eDouble = e.numberDouble();
// NaN doubles are rejected.
if (std::isnan(eDouble)) {
mongoutils::str::stream ss;
ss << "bit positions cannot take a NaN: " << e;
return Status(ErrorCodes::BadValue, ss);
}
// This makes sure e does not overflow a 32-bit integer container.
if (eDouble > std::numeric_limits<int>::max() ||
eDouble < std::numeric_limits<int>::min()) {
mongoutils::str::stream ss;
ss << "bit positions cannot be represented as a 32-bit signed integer: " << e;
return Status(ErrorCodes::BadValue, ss);
}
// This checks if e is integral.
if (eDouble != static_cast<double>(static_cast<long long>(eDouble))) {
mongoutils::str::stream ss;
ss << "bit positions must be an integer but got: " << e;
return Status(ErrorCodes::BadValue, ss);
}
}
if (e.type() == BSONType::NumberLong) {
long long eLong = e.numberLong();
// This makes sure e does not overflow a 32-bit integer container.
if (eLong > std::numeric_limits<int>::max() ||
eLong < std::numeric_limits<int>::min()) {
mongoutils::str::stream ss;
ss << "bit positions cannot be represented as a 32-bit signed integer: " << e;
return Status(ErrorCodes::BadValue, ss);
}
}
int eValue = e.numberInt();
// No negatives.
if (eValue < 0) {
mongoutils::str::stream ss;
ss << "bit positions must be >= 0 but got: " << e;
return Status(ErrorCodes::BadValue, ss);
}
bitPositions.push_back(eValue);
}
return bitPositions;
}
StatusWith<long long> MatchExpressionParser::parseIntegerElementToNonNegativeLong(
BSONElement elem) {
auto number = parseIntegerElementToLong(elem);
if (!number.isOK()) {
return number;
}
if (number.getValue() < 0) {
return Status(ErrorCodes::FailedToParse,
str::stream() << "Expected a positive number in: " << elem);
}
return number;
}
StatusWith<long long> MatchExpressionParser::parseIntegerElementToLong(BSONElement elem) {
if (!elem.isNumber()) {
return Status(ErrorCodes::FailedToParse, str::stream() << "Expected a number in: " << elem);
}
long long number = 0;
if (elem.type() == BSONType::NumberDouble) {
double eDouble = elem.numberDouble();
// NaN doubles are rejected.
if (std::isnan(eDouble)) {
return Status(ErrorCodes::FailedToParse,
str::stream() << "Expected an integer, but found NaN in: " << elem);
}
// No integral doubles that are too large to be represented as a 64 bit signed integer.
// We use 'kLongLongMaxAsDouble' because if we just did eDouble > 2^63-1, it would be
// compared against 2^63. eDouble=2^63 would not get caught that way.
if (eDouble >= MatchExpressionParser::kLongLongMaxPlusOneAsDouble ||
eDouble < std::numeric_limits<long long>::min()) {
return Status(ErrorCodes::FailedToParse,
str::stream() << "Cannot represent as a 64-bit integer: " << elem);
}
// This checks if elem is an integral double.
if (eDouble != static_cast<double>(static_cast<long long>(eDouble))) {
return Status(ErrorCodes::FailedToParse,
str::stream() << "Expected an integer: " << elem);
}
number = elem.numberLong();
} else if (elem.type() == BSONType::NumberDecimal) {
uint32_t signalingFlags = Decimal128::kNoFlag;
number = elem.numberDecimal().toLongExact(&signalingFlags);
if (signalingFlags != Decimal128::kNoFlag) {
return Status(ErrorCodes::FailedToParse,
str::stream() << "Cannot represent as a 64-bit integer: " << elem);
}
} else {
number = elem.numberLong();
}
return number;
}
StatusWithMatchExpression MatchExpressionParser::_parseInternalSchemaFmod(const char* name,
const BSONElement& elem) {
StringData path(name);
if (elem.type() != Array)
return {ErrorCodes::BadValue,
str::stream() << path << " must be an array, but got type " << elem.type()};
BSONObjIterator i(elem.embeddedObject());
if (!i.more())
return {ErrorCodes::BadValue, str::stream() << path << " does not have enough elements"};
BSONElement d = i.next();
if (!d.isNumber())
return {ErrorCodes::TypeMismatch,
str::stream() << path << " does not have a numeric divisor"};
if (!i.more())
return {ErrorCodes::BadValue, str::stream() << path << " does not have enough elements"};
BSONElement r = i.next();
if (!d.isNumber())
return {ErrorCodes::TypeMismatch,
str::stream() << path << " does not have a numeric remainder"};
if (i.more())
return {ErrorCodes::BadValue, str::stream() << path << " has too many elements"};
std::unique_ptr<InternalSchemaFmodMatchExpression> result =
stdx::make_unique<InternalSchemaFmodMatchExpression>();
Status s = result->init(name, d.numberDecimal(), r.numberDecimal());
if (!s.isOK())
return s;
return {std::move(result)};
}
template <class T>
StatusWithMatchExpression MatchExpressionParser::_parseInternalSchemaFixedArityArgument(
StringData name,
const BSONElement& input,
const boost::intrusive_ptr<ExpressionContext>& expCtx,
AllowedFeatureSet allowedFeatures) {
constexpr auto arity = T::arity();
if (input.type() != BSONType::Array) {
return {ErrorCodes::FailedToParse,
str::stream() << name << " must be an array of " << arity << " MatchExpressions"};
}
auto inputObj = input.embeddedObject();
if (static_cast<size_t>(inputObj.nFields()) != arity) {
return {ErrorCodes::FailedToParse,
str::stream() << name << " requires exactly " << arity
<< " MatchExpressions, but got "
<< inputObj.nFields()};
}
// Fill out 'expressions' with all of the parsed subexpressions contained in the array, tracking
// our location in the array with 'position'.
std::array<std::unique_ptr<MatchExpression>, arity> expressions;
auto position = expressions.begin();
for (const auto& elem : inputObj) {
if (elem.type() != BSONType::Object) {
return {ErrorCodes::FailedToParse,
str::stream() << name
<< " must be an array of objects, but found an element of type "
<< elem.type()};
}
const bool isTopLevel = false;
auto subexpr = _parse(elem.embeddedObject(), expCtx, allowedFeatures, isTopLevel);
if (!subexpr.isOK()) {
return subexpr.getStatus();
}
*position = std::move(subexpr.getValue());
++position;
}
auto parsedExpression = stdx::make_unique<T>();
parsedExpression->init(std::move(expressions));
return {std::move(parsedExpression)};
}
template <class T>
StatusWithMatchExpression MatchExpressionParser::_parseInternalSchemaSingleIntegerArgument(
const char* name, const BSONElement& elem) const {
auto parsedInt = parseIntegerElementToNonNegativeLong(elem);
if (!parsedInt.isOK()) {
return parsedInt.getStatus();
}
auto matchExpression = stdx::make_unique<T>();
auto status = matchExpression->init(name, parsedInt.getValue());
if (!status.isOK()) {
return status;
}
return {std::move(matchExpression)};
}
template <class T>
StatusWithMatchExpression MatchExpressionParser::_parseTopLevelInternalSchemaSingleIntegerArgument(
const BSONElement& elem) const {
auto parsedInt = parseIntegerElementToNonNegativeLong(elem);
if (!parsedInt.isOK()) {
return parsedInt.getStatus();
}
auto matchExpression = stdx::make_unique<T>();
auto status = matchExpression->init(parsedInt.getValue());
if (!status.isOK()) {
return status;
}
return {std::move(matchExpression)};
}
namespace {
/**
* Looks at the field named 'namePlaceholderFieldName' within 'containingObject' and parses a name
* placeholder from that element. 'expressionName' is the name of the expression that requires the
* name placeholder and is used to generate helpful error messages.
*/
StatusWith<StringData> parseNamePlaceholder(const BSONObj& containingObject,
StringData namePlaceholderFieldName,
StringData expressionName) {
auto namePlaceholderElem = containingObject[namePlaceholderFieldName];
if (!namePlaceholderElem) {
return {ErrorCodes::FailedToParse,
str::stream() << expressionName << " requires a '" << namePlaceholderFieldName
<< "'"};
} else if (namePlaceholderElem.type() != BSONType::String) {
return {ErrorCodes::TypeMismatch,
str::stream() << expressionName << " requires '" << namePlaceholderFieldName
<< "' to be a string, not "
<< namePlaceholderElem.type()};
}
return {namePlaceholderElem.valueStringData()};
}
/**
* Looks at the field named 'exprWithPlaceholderFieldName' within 'containingObject' and parses an
* ExpressionWithPlaceholder from that element. Fails if an error occurs during parsing, or if the
* ExpressionWithPlaceholder has a different name placeholder than 'expectedPlaceholder'.
* 'expressionName' is the name of the expression that requires the ExpressionWithPlaceholder and is
* used to generate helpful error messages.
*/
StatusWith<std::unique_ptr<ExpressionWithPlaceholder>> parseExprWithPlaceholder(
const BSONObj& containingObject,
StringData exprWithPlaceholderFieldName,
StringData expressionName,
StringData expectedPlaceholder,
const boost::intrusive_ptr<ExpressionContext>& expCtx) {
auto exprWithPlaceholderElem = containingObject[exprWithPlaceholderFieldName];
if (!exprWithPlaceholderElem) {
return {ErrorCodes::FailedToParse,
str::stream() << expressionName << " requires '" << exprWithPlaceholderFieldName
<< "'"};
} else if (exprWithPlaceholderElem.type() != BSONType::Object) {
return {ErrorCodes::TypeMismatch,
str::stream() << expressionName << " found '" << exprWithPlaceholderFieldName
<< "', which is an incompatible type: "
<< exprWithPlaceholderElem.type()};
}
auto result =
ExpressionWithPlaceholder::parse(exprWithPlaceholderElem.embeddedObject(), expCtx);
if (!result.isOK()) {
return result.getStatus();
}
auto placeholder = result.getValue()->getPlaceholder();
if (placeholder && (*placeholder != expectedPlaceholder)) {
return {ErrorCodes::FailedToParse,
str::stream() << expressionName << " expected a name placeholder of "
<< expectedPlaceholder
<< ", but '"
<< exprWithPlaceholderElem.fieldName()
<< "' has a mismatching placeholder '"
<< *placeholder
<< "'"};
}
return result;
}
StatusWith<std::vector<InternalSchemaAllowedPropertiesMatchExpression::PatternSchema>>
parsePatternProperties(BSONElement patternPropertiesElem,
StringData expectedPlaceholder,
const boost::intrusive_ptr<ExpressionContext>& expCtx) {
if (!patternPropertiesElem) {
return {ErrorCodes::FailedToParse,
str::stream() << InternalSchemaAllowedPropertiesMatchExpression::kName
<< " requires 'patternProperties'"};
} else if (patternPropertiesElem.type() != BSONType::Array) {
return {ErrorCodes::TypeMismatch,
str::stream() << InternalSchemaAllowedPropertiesMatchExpression::kName
<< " requires 'patternProperties' to be an array, not "
<< patternPropertiesElem.type()};
}
std::vector<InternalSchemaAllowedPropertiesMatchExpression::PatternSchema> patternProperties;
for (auto&& constraintElem : patternPropertiesElem.embeddedObject()) {
if (constraintElem.type() != BSONType::Object) {
return {ErrorCodes::TypeMismatch,
str::stream() << InternalSchemaAllowedPropertiesMatchExpression::kName
<< " requires 'patternProperties' to be an array of objects"};
}
auto constraint = constraintElem.embeddedObject();
if (constraint.nFields() != 2) {
return {ErrorCodes::FailedToParse,
str::stream() << InternalSchemaAllowedPropertiesMatchExpression::kName
<< " requires 'patternProperties' to be an array of objects "
"containing exactly two fields, 'regex' and 'expression'"};
}
auto expressionWithPlaceholder =
parseExprWithPlaceholder(constraint,
"expression"_sd,
InternalSchemaAllowedPropertiesMatchExpression::kName,
expectedPlaceholder,
expCtx);
if (!expressionWithPlaceholder.isOK()) {
return expressionWithPlaceholder.getStatus();
}
auto regexElem = constraint["regex"];
if (!regexElem) {
return {
ErrorCodes::FailedToParse,
str::stream() << InternalSchemaAllowedPropertiesMatchExpression::kName
<< " requires each object in 'patternProperties' to have a 'regex'"};
}
if (regexElem.type() != BSONType::RegEx) {
return {ErrorCodes::TypeMismatch,
str::stream() << InternalSchemaAllowedPropertiesMatchExpression::kName
<< " requires 'patternProperties' to be an array of objects, "
"where 'regex' is a regular expression"};
} else if (*regexElem.regexFlags() != '\0') {
return {
ErrorCodes::BadValue,
str::stream()
<< InternalSchemaAllowedPropertiesMatchExpression::kName
<< " does not accept regex flags for pattern schemas in 'patternProperties'"};
}
patternProperties.emplace_back(
InternalSchemaAllowedPropertiesMatchExpression::Pattern(regexElem.regex()),
std::move(expressionWithPlaceholder.getValue()));
}
return std::move(patternProperties);
}
StatusWith<boost::container::flat_set<StringData>> parseProperties(BSONElement propertiesElem) {
if (!propertiesElem) {
return {ErrorCodes::FailedToParse,
str::stream() << InternalSchemaAllowedPropertiesMatchExpression::kName
<< " requires 'properties' to be present"};
} else if (propertiesElem.type() != BSONType::Array) {
return {ErrorCodes::TypeMismatch,
str::stream() << InternalSchemaAllowedPropertiesMatchExpression::kName
<< " requires 'properties' to be an array, not "
<< propertiesElem.type()};
}
std::vector<StringData> properties;
for (auto&& property : propertiesElem.embeddedObject()) {
if (property.type() != BSONType::String) {
return {
ErrorCodes::TypeMismatch,
str::stream() << InternalSchemaAllowedPropertiesMatchExpression::kName
<< " requires 'properties' to be an array of strings, but found a "
<< property.type()};
}
properties.push_back(property.valueStringData());
}
return boost::container::flat_set<StringData>(properties.begin(), properties.end());
}
} // namespace
StatusWithMatchExpression MatchExpressionParser::_parseInternalSchemaMatchArrayIndex(
const char* path,
const BSONElement& elem,
const boost::intrusive_ptr<ExpressionContext>& expCtx) {
if (elem.type() != BSONType::Object) {
return {ErrorCodes::TypeMismatch,
str::stream() << InternalSchemaMatchArrayIndexMatchExpression::kName
<< " must be an object"};
}
auto subobj = elem.embeddedObject();
if (subobj.nFields() != 3) {
return {ErrorCodes::FailedToParse,
str::stream() << InternalSchemaMatchArrayIndexMatchExpression::kName
<< " requires exactly three fields: 'index', "
"'namePlaceholder' and 'expression'"};
}
auto index = parseIntegerElementToNonNegativeLong(subobj["index"]);
if (!index.isOK()) {
return index.getStatus();
}
auto namePlaceholder = parseNamePlaceholder(
subobj, "namePlaceholder"_sd, InternalSchemaMatchArrayIndexMatchExpression::kName);
if (!namePlaceholder.isOK()) {
return namePlaceholder.getStatus();
}
auto expressionWithPlaceholder =
parseExprWithPlaceholder(subobj,
"expression"_sd,
InternalSchemaMatchArrayIndexMatchExpression::kName,
namePlaceholder.getValue(),
expCtx);
if (!expressionWithPlaceholder.isOK()) {
return expressionWithPlaceholder.getStatus();
}
auto matchArrayIndexExpr = stdx::make_unique<InternalSchemaMatchArrayIndexMatchExpression>();
auto initStatus = matchArrayIndexExpr->init(
path, index.getValue(), std::move(expressionWithPlaceholder.getValue()));
if (!initStatus.isOK()) {
return initStatus;
}
return {std::move(matchArrayIndexExpr)};
}
StatusWithMatchExpression MatchExpressionParser::_parseInternalSchemaAllowedProperties(
const BSONElement& elem, const boost::intrusive_ptr<ExpressionContext>& expCtx) {
if (elem.type() != BSONType::Object) {
return {ErrorCodes::TypeMismatch,
str::stream() << InternalSchemaAllowedPropertiesMatchExpression::kName
<< " must be an object"};
}
auto subobj = elem.embeddedObject();
if (subobj.nFields() != 4) {
return {ErrorCodes::FailedToParse,
str::stream() << InternalSchemaAllowedPropertiesMatchExpression::kName
<< " requires exactly four fields: 'properties', 'namePlaceholder', "
"'patternProperties' and 'otherwise'"};
}
auto namePlaceholder = parseNamePlaceholder(
subobj, "namePlaceholder"_sd, InternalSchemaAllowedPropertiesMatchExpression::kName);
if (!namePlaceholder.isOK()) {
return namePlaceholder.getStatus();
}
auto patternProperties =
parsePatternProperties(subobj["patternProperties"], namePlaceholder.getValue(), expCtx);
if (!patternProperties.isOK()) {
return patternProperties.getStatus();
}
auto otherwise = parseExprWithPlaceholder(subobj,
"otherwise"_sd,
InternalSchemaAllowedPropertiesMatchExpression::kName,
namePlaceholder.getValue(),
expCtx);
if (!otherwise.isOK()) {
return otherwise.getStatus();
}
auto properties = parseProperties(subobj["properties"]);
if (!properties.isOK()) {
return properties.getStatus();
}
auto allowedPropertiesExpr =
stdx::make_unique<InternalSchemaAllowedPropertiesMatchExpression>();
auto status = allowedPropertiesExpr->init(std::move(properties.getValue()),
namePlaceholder.getValue(),
std::move(patternProperties.getValue()),
std::move(otherwise.getValue()));
if (!status.isOK()) {
return status;
}
return {std::move(allowedPropertiesExpr)};
}
StatusWithMatchExpression MatchExpressionParser::_parseGeo(const char* name,
PathAcceptingKeyword type,
const BSONObj& section,
AllowedFeatureSet allowedFeatures) {
if (PathAcceptingKeyword::WITHIN == type || PathAcceptingKeyword::GEO_INTERSECTS == type) {
std::unique_ptr<GeoExpression> gq = stdx::make_unique<GeoExpression>(name);
Status parseStatus = gq->parseFrom(section);
if (!parseStatus.isOK())
return StatusWithMatchExpression(parseStatus);
std::unique_ptr<GeoMatchExpression> e = stdx::make_unique<GeoMatchExpression>();
Status s = e->init(name, gq.release(), section);
if (!s.isOK())
return StatusWithMatchExpression(s);
return {std::move(e)};
} else {
invariant(PathAcceptingKeyword::GEO_NEAR == type);
if ((allowedFeatures & AllowedFeatures::kGeoNear) == 0u) {
return {Status(ErrorCodes::BadValue,
"$geoNear, $near, and $nearSphere are not allowed in this context")};
}
std::unique_ptr<GeoNearExpression> nq = stdx::make_unique<GeoNearExpression>(name);
Status s = nq->parseFrom(section);
if (!s.isOK()) {
return StatusWithMatchExpression(s);
}
std::unique_ptr<GeoNearMatchExpression> e = stdx::make_unique<GeoNearMatchExpression>();
s = e->init(name, nq.release(), section);
if (!s.isOK())
return StatusWithMatchExpression(s);
return {std::move(e)};
}
}
StatusWithMatchExpression MatchExpressionParser::_parseExpr(
BSONElement elem,
AllowedFeatureSet allowedFeatures,
const boost::intrusive_ptr<ExpressionContext>& expCtx) {
if ((allowedFeatures & AllowedFeatures::kExpr) == 0u) {
return {Status(ErrorCodes::BadValue, "$expr is not allowed in this context")};
}
invariant(expCtx);
return {stdx::make_unique<ExprMatchExpression>(std::move(elem), expCtx)};
}
namespace {
// Maps from query operator string name to operator PathAcceptingKeyword.
std::unique_ptr<StringMap<PathAcceptingKeyword>> queryOperatorMap;
MONGO_INITIALIZER(MatchExpressionParser)(InitializerContext* context) {
queryOperatorMap =
stdx::make_unique<StringMap<PathAcceptingKeyword>>(StringMap<PathAcceptingKeyword>{
// TODO: SERVER-19565 Add $eq after auditing callers.
{"_internalSchemaAllElemMatchFromIndex",
PathAcceptingKeyword::INTERNAL_SCHEMA_ALL_ELEM_MATCH_FROM_INDEX},
{"_internalSchemaEq", PathAcceptingKeyword::INTERNAL_SCHEMA_EQ},
{"_internalSchemaFmod", PathAcceptingKeyword::INTERNAL_SCHEMA_FMOD},
{"_internalSchemaMatchArrayIndex",
PathAcceptingKeyword::INTERNAL_SCHEMA_MATCH_ARRAY_INDEX},
{"_internalSchemaMaxItems", PathAcceptingKeyword::INTERNAL_SCHEMA_MAX_ITEMS},
{"_internalSchemaMaxLength", PathAcceptingKeyword::INTERNAL_SCHEMA_MAX_LENGTH},
{"_internalSchemaMinItems", PathAcceptingKeyword::INTERNAL_SCHEMA_MIN_ITEMS},
{"_internalSchemaMinItems", PathAcceptingKeyword::INTERNAL_SCHEMA_MIN_ITEMS},
{"_internalSchemaMinLength", PathAcceptingKeyword::INTERNAL_SCHEMA_MIN_LENGTH},
{"_internalSchemaObjectMatch", PathAcceptingKeyword::INTERNAL_SCHEMA_OBJECT_MATCH},
{"_internalSchemaType", PathAcceptingKeyword::INTERNAL_SCHEMA_TYPE},
{"_internalSchemaUniqueItems", PathAcceptingKeyword::INTERNAL_SCHEMA_UNIQUE_ITEMS},
{"all", PathAcceptingKeyword::ALL},
{"bitsAllClear", PathAcceptingKeyword::BITS_ALL_CLEAR},
{"bitsAllSet", PathAcceptingKeyword::BITS_ALL_SET},
{"bitsAnyClear", PathAcceptingKeyword::BITS_ANY_CLEAR},
{"bitsAnySet", PathAcceptingKeyword::BITS_ANY_SET},
{"elemMatch", PathAcceptingKeyword::ELEM_MATCH},
{"exists", PathAcceptingKeyword::EXISTS},
{"geoIntersects", PathAcceptingKeyword::GEO_INTERSECTS},
{"geoNear", PathAcceptingKeyword::GEO_NEAR},
{"geoWithin", PathAcceptingKeyword::WITHIN},
{"gt", PathAcceptingKeyword::GREATER_THAN},
{"gte", PathAcceptingKeyword::GREATER_THAN_OR_EQUAL},
{"in", PathAcceptingKeyword::IN_EXPR},
{"lt", PathAcceptingKeyword::LESS_THAN},
{"lte", PathAcceptingKeyword::LESS_THAN_OR_EQUAL},
{"mod", PathAcceptingKeyword::MOD},
{"ne", PathAcceptingKeyword::NOT_EQUAL},
{"near", PathAcceptingKeyword::GEO_NEAR},
{"nearSphere", PathAcceptingKeyword::GEO_NEAR},
{"nin", PathAcceptingKeyword::NOT_IN},
{"options", PathAcceptingKeyword::OPTIONS},
{"regex", PathAcceptingKeyword::REGEX},
{"size", PathAcceptingKeyword::SIZE},
{"type", PathAcceptingKeyword::TYPE},
{"within", PathAcceptingKeyword::WITHIN},
});
return Status::OK();
}
} // anonymous namespace
boost::optional<PathAcceptingKeyword> MatchExpressionParser::parsePathAcceptingKeyword(
BSONElement typeElem, boost::optional<PathAcceptingKeyword> defaultKeyword) {
auto fieldName = typeElem.fieldName();
if (fieldName[0] == '$' && fieldName[1]) {
auto opName = typeElem.fieldNameStringData().substr(1);
auto queryOp = queryOperatorMap->find(opName);
if (queryOp == queryOperatorMap->end()) {
return defaultKeyword;
}
return queryOp->second;
}
return defaultKeyword;
}
} // namespace mongo
|