-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Criteria.java
1428 lines (1216 loc) · 43.8 KB
/
Criteria.java
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
/*
* Copyright 2010-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.core.query;
import static org.springframework.util.ObjectUtils.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.bson.BsonRegularExpression;
import org.bson.BsonType;
import org.bson.Document;
import org.bson.types.Binary;
import org.springframework.data.domain.Example;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Point;
import org.springframework.data.geo.Shape;
import org.springframework.data.mongodb.InvalidMongoDbApiUsageException;
import org.springframework.data.mongodb.core.geo.GeoJson;
import org.springframework.data.mongodb.core.geo.Sphere;
import org.springframework.data.mongodb.core.schema.JsonSchemaObject.Type;
import org.springframework.data.mongodb.core.schema.JsonSchemaProperty;
import org.springframework.data.mongodb.core.schema.MongoJsonSchema;
import org.springframework.data.mongodb.util.RegexFlags;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.Base64Utils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import com.mongodb.BasicDBList;
/**
* Central class for creating queries. It follows a fluent API style so that you can easily chain together multiple
* criteria. Static import of the {@link Criteria#where Criteria.where} method improves readability.
*
* @author Thomas Risberg
* @author Oliver Gierke
* @author Thomas Darimont
* @author Christoph Strobl
* @author Mark Paluch
* @author Andreas Zink
* @author Ziemowit Stolarczyk
* @author Clément Petit
* @author James McNee
*/
public class Criteria implements CriteriaDefinition {
/**
* Custom "not-null" object as we have to be able to work with {@literal null} values as well.
*/
private static final Object NOT_SET = new Object();
private @Nullable String key;
private List<Criteria> criteriaChain;
private LinkedHashMap<String, Object> criteria = new LinkedHashMap<String, Object>();
private @Nullable Object isValue = NOT_SET;
public Criteria() {
this.criteriaChain = new ArrayList<Criteria>();
}
public Criteria(String key) {
this.criteriaChain = new ArrayList<Criteria>();
this.criteriaChain.add(this);
this.key = key;
}
protected Criteria(List<Criteria> criteriaChain, String key) {
this.criteriaChain = criteriaChain;
this.criteriaChain.add(this);
this.key = key;
}
/**
* Static factory method to create a Criteria using the provided key
*
* @param key the property or field name.
* @return new instance of {@link Criteria}.
*/
public static Criteria where(String key) {
return new Criteria(key);
}
/**
* Static factory method to create a {@link Criteria} matching an example object.
*
* @param example must not be {@literal null}.
* @return new instance of {@link Criteria}.
* @see Criteria#alike(Example)
* @since 1.8
*/
public static Criteria byExample(Object example) {
return byExample(Example.of(example));
}
/**
* Static factory method to create a {@link Criteria} matching an example object. <br />
* By default the {@link Example} uses typed matching restricting it to probe assignable types. For example, when
* sticking with the default type key ({@code _class}), the query has restrictions such as
* <code>_class : { $in : [com.acme.Person] } </code>. <br />
* To avoid the above mentioned type restriction use an {@link UntypedExampleMatcher} with
* {@link Example#of(Object, org.springframework.data.domain.ExampleMatcher)}.
*
* @param example must not be {@literal null}.
* @return new instance of {@link Criteria}.
* @see Criteria#alike(Example)
* @since 1.8
*/
public static Criteria byExample(Example<?> example) {
return new Criteria().alike(example);
}
/**
* Static factory method to create a {@link Criteria} matching documents against a given structure defined by the
* {@link MongoJsonSchema} using ({@code $jsonSchema}) operator.
*
* @param schema must not be {@literal null}.
* @return this
* @since 2.1
* @see <a href="https://docs.mongodb.com/manual/reference/operator/query/jsonSchema/">MongoDB Query operator:
* $jsonSchema</a>
*/
public static Criteria matchingDocumentStructure(MongoJsonSchema schema) {
return new Criteria().andDocumentStructureMatches(schema);
}
/**
* Static factory method to create a Criteria using the provided key
*
* @return new instance of {@link Criteria}.
*/
public Criteria and(String key) {
return new Criteria(this.criteriaChain, key);
}
/**
* Creates a criterion using equality
*
* @param value can be {@literal null}.
* @return this.
*/
public Criteria is(@Nullable Object value) {
if (!isValue.equals(NOT_SET)) {
throw new InvalidMongoDbApiUsageException(
"Multiple 'is' values declared. You need to use 'and' with multiple criteria");
}
if (lastOperatorWasNot()) {
throw new InvalidMongoDbApiUsageException("Invalid query: 'not' can't be used with 'is' - use 'ne' instead.");
}
this.isValue = value;
return this;
}
/**
* Creates a criterion using {@literal null} equality comparison which matches documents that either contain the item
* field whose value is {@literal null} or that do not contain the item field.
* <br />
* Use {@link #isNullValue()} to only query for documents that contain the field whose value is equal to
* {@link org.bson.BsonType#NULL}. <br />
* Use {@link #exists(boolean)} to query for documents that do (not) contain the field.
*
* @return this.
* @see <a href="https://docs.mongodb.com/manual/tutorial/query-for-null-fields/#equality-filter">Query for Null or
* Missing Fields: Equality Filter</a>
* @since 3.3
*/
public Criteria isNull() {
return is(null);
}
/**
* Creates a criterion using a {@link org.bson.BsonType} comparison which matches only documents that contain the item
* field whose value is equal to {@link org.bson.BsonType#NULL}.
* <br />
* Use {@link #isNull()} to query for documents that contain the field with a {@literal null} value or do not contain the
* field at all. <br />
* Use {@link #exists(boolean)} to query for documents that do (not) contain the field.
*
* @return this.
* @see <a href="https://docs.mongodb.com/manual/tutorial/query-for-null-fields/#type-check">Query for Null or Missing
* Fields: Type Check</a>
* @since 3.3
*/
public Criteria isNullValue() {
criteria.put("$type", BsonType.NULL.getValue());
return this;
}
private boolean lastOperatorWasNot() {
return !this.criteria.isEmpty() && "$not".equals(this.criteria.keySet().toArray()[this.criteria.size() - 1]);
}
/**
* Creates a criterion using the {@literal $ne} operator.
*
* @param value can be {@literal null}.
* @return this.
* @see <a href="https://docs.mongodb.com/manual/reference/operator/query/ne/">MongoDB Query operator: $ne</a>
*/
public Criteria ne(@Nullable Object value) {
criteria.put("$ne", value);
return this;
}
/**
* Creates a criterion using the {@literal $lt} operator.
*
* @param value must not be {@literal null}.
* @return this.
* @see <a href="https://docs.mongodb.com/manual/reference/operator/query/lt/">MongoDB Query operator: $lt</a>
*/
public Criteria lt(Object value) {
criteria.put("$lt", value);
return this;
}
/**
* Creates a criterion using the {@literal $lte} operator.
*
* @param value must not be {@literal null}.
* @return this.
* @see <a href="https://docs.mongodb.com/manual/reference/operator/query/lte/">MongoDB Query operator: $lte</a>
*/
public Criteria lte(Object value) {
criteria.put("$lte", value);
return this;
}
/**
* Creates a criterion using the {@literal $gt} operator.
*
* @param value must not be {@literal null}.
* @return this.
* @see <a href="https://docs.mongodb.com/manual/reference/operator/query/gt/">MongoDB Query operator: $gt</a>
*/
public Criteria gt(Object value) {
criteria.put("$gt", value);
return this;
}
/**
* Creates a criterion using the {@literal $gte} operator.
*
* @param value can be {@literal null}.
* @return this.
* @see <a href="https://docs.mongodb.com/manual/reference/operator/query/gte/">MongoDB Query operator: $gte</a>
*/
public Criteria gte(Object value) {
criteria.put("$gte", value);
return this;
}
/**
* Creates a criterion using the {@literal $in} operator.
*
* @param values the values to match against
* @return this.
* @see <a href="https://docs.mongodb.com/manual/reference/operator/query/in/">MongoDB Query operator: $in</a>
*/
public Criteria in(Object... values) {
if (values.length > 1 && values[1] instanceof Collection) {
throw new InvalidMongoDbApiUsageException(
"You can only pass in one argument of type " + values[1].getClass().getName());
}
criteria.put("$in", Arrays.asList(values));
return this;
}
/**
* Creates a criterion using the {@literal $in} operator.
*
* @param values the collection containing the values to match against
* @return this.
* @see <a href="https://docs.mongodb.com/manual/reference/operator/query/in/">MongoDB Query operator: $in</a>
*/
public Criteria in(Collection<?> values) {
criteria.put("$in", values);
return this;
}
/**
* Creates a criterion using the {@literal $nin} operator.
*
* @param values
* @return this.
* @see <a href="https://docs.mongodb.com/manual/reference/operator/query/nin/">MongoDB Query operator: $nin</a>
*/
public Criteria nin(Object... values) {
return nin(Arrays.asList(values));
}
/**
* Creates a criterion using the {@literal $nin} operator.
*
* @param values must not be {@literal null}.
* @return this.
* @see <a href="https://docs.mongodb.com/manual/reference/operator/query/nin/">MongoDB Query operator: $nin</a>
*/
public Criteria nin(Collection<?> values) {
criteria.put("$nin", values);
return this;
}
/**
* Creates a criterion using the {@literal $mod} operator.
*
* @param value must not be {@literal null}.
* @param remainder must not be {@literal null}.
* @return this.
* @see <a href="https://docs.mongodb.com/manual/reference/operator/query/mod/">MongoDB Query operator: $mod</a>
*/
public Criteria mod(Number value, Number remainder) {
List<Object> l = new ArrayList<Object>(2);
l.add(value);
l.add(remainder);
criteria.put("$mod", l);
return this;
}
/**
* Creates a criterion using the {@literal $all} operator.
*
* @param values must not be {@literal null}.
* @return this.
* @see <a href="https://docs.mongodb.com/manual/reference/operator/query/all/">MongoDB Query operator: $all</a>
*/
public Criteria all(Object... values) {
return all(Arrays.asList(values));
}
/**
* Creates a criterion using the {@literal $all} operator.
*
* @param values must not be {@literal null}.
* @return this.
* @see <a href="https://docs.mongodb.com/manual/reference/operator/query/all/">MongoDB Query operator: $all</a>
*/
public Criteria all(Collection<?> values) {
criteria.put("$all", values);
return this;
}
/**
* Creates a criterion using the {@literal $size} operator.
*
* @param size
* @return this.
* @see <a href="https://docs.mongodb.com/manual/reference/operator/query/size/">MongoDB Query operator: $size</a>
*/
public Criteria size(int size) {
criteria.put("$size", size);
return this;
}
/**
* Creates a criterion using the {@literal $exists} operator.
*
* @param value
* @return this.
* @see <a href="https://docs.mongodb.com/manual/reference/operator/query/exists/">MongoDB Query operator: $exists</a>
*/
public Criteria exists(boolean value) {
criteria.put("$exists", value);
return this;
}
/**
* Creates a criterion using the {@literal $sampleRate} operator.
*
* @param sampleRate sample rate to determine number of documents to be randomly selected from the input. Must be
* between {@code 0} and {@code 1}.
* @return this.
* @see <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/sampleRate/">MongoDB Query operator:
* $sampleRate</a>
* @since 3.3
*/
public Criteria sampleRate(double sampleRate) {
Assert.isTrue(sampleRate >= 0, "The sample rate must be greater than zero!");
Assert.isTrue(sampleRate <= 1, "The sample rate must not be greater than one!");
criteria.put("$sampleRate", sampleRate);
return this;
}
/**
* Creates a criterion using the {@literal $type} operator.
*
* @param typeNumber
* @return this.
* @see <a href="https://docs.mongodb.com/manual/reference/operator/query/type/">MongoDB Query operator: $type</a>
*/
public Criteria type(int typeNumber) {
criteria.put("$type", typeNumber);
return this;
}
/**
* Creates a criterion using the {@literal $type} operator.
*
* @param types must not be {@literal null}.
* @return this.
* @since 2.1
* @see <a href="https://docs.mongodb.com/manual/reference/operator/query/type/">MongoDB Query operator: $type</a>
*/
public Criteria type(Type... types) {
Assert.notNull(types, "Types must not be null!");
Assert.noNullElements(types, "Types must not contain null.");
return type(Arrays.asList(types));
}
/**
* Creates a criterion using the {@literal $type} operator.
*
* @param types must not be {@literal null}.
* @return this.
* @since 3.2
* @see <a href="https://docs.mongodb.com/manual/reference/operator/query/type/">MongoDB Query operator: $type</a>
*/
public Criteria type(Collection<Type> types) {
Assert.notNull(types, "Types must not be null!");
criteria.put("$type", types.stream().map(Type::toBsonType).map(Type::value).collect(Collectors.toList()));
return this;
}
/**
* Creates a criterion using the {@literal $not} meta operator which affects the clause directly following
*
* @return this.
* @see <a href="https://docs.mongodb.com/manual/reference/operator/query/not/">MongoDB Query operator: $not</a>
*/
public Criteria not() {
return not(null);
}
/**
* Creates a criterion using the {@literal $not} operator.
*
* @param value can be {@literal null}.
* @return this.
* @see <a href="https://docs.mongodb.com/manual/reference/operator/query/not/">MongoDB Query operator: $not</a>
*/
private Criteria not(@Nullable Object value) {
criteria.put("$not", value);
return this;
}
/**
* Creates a criterion using a {@literal $regex} operator.
*
* @param regex must not be {@literal null}.
* @return this.
* @see <a href="https://docs.mongodb.com/manual/reference/operator/query/regex/">MongoDB Query operator: $regex</a>
*/
public Criteria regex(String regex) {
return regex(regex, null);
}
/**
* Creates a criterion using a {@literal $regex} and {@literal $options} operator.
*
* @param regex must not be {@literal null}.
* @param options can be {@literal null}.
* @return this.
* @see <a href="https://docs.mongodb.com/manual/reference/operator/query/regex/">MongoDB Query operator: $regex</a>
*/
public Criteria regex(String regex, @Nullable String options) {
return regex(toPattern(regex, options));
}
/**
* Syntactical sugar for {@link #is(Object)} making obvious that we create a regex predicate.
*
* @param pattern must not be {@literal null}.
* @return this.
*/
public Criteria regex(Pattern pattern) {
Assert.notNull(pattern, "Pattern must not be null!");
if (lastOperatorWasNot()) {
return not(pattern);
}
this.isValue = pattern;
return this;
}
/**
* Use a MongoDB native {@link BsonRegularExpression}.
*
* @param regex must not be {@literal null}.
* @return this.
*/
public Criteria regex(BsonRegularExpression regex) {
if (lastOperatorWasNot()) {
return not(regex);
}
this.isValue = regex;
return this;
}
private Pattern toPattern(String regex, @Nullable String options) {
Assert.notNull(regex, "Regex string must not be null!");
return Pattern.compile(regex, RegexFlags.toRegexFlags(options));
}
/**
* Creates a geospatial criterion using a {@literal $geoWithin $centerSphere} operation. This is only available for
* Mongo 2.4 and higher.
*
* @param circle must not be {@literal null}
* @return this.
* @see <a href="https://docs.mongodb.com/manual/reference/operator/query/geoWithin/">MongoDB Query operator:
* $geoWithin</a>
* @see <a href="https://docs.mongodb.com/manual/reference/operator/query/centerSphere/">MongoDB Query operator:
* $centerSphere</a>
*/
public Criteria withinSphere(Circle circle) {
Assert.notNull(circle, "Circle must not be null!");
criteria.put("$geoWithin", new GeoCommand(new Sphere(circle)));
return this;
}
/**
* Creates a geospatial criterion using a {@literal $geoWithin} operation.
*
* @param shape must not be {@literal null}.
* @return this.
* @see <a href="https://docs.mongodb.com/manual/reference/operator/query/geoWithin/">MongoDB Query operator:
* $geoWithin</a>
*/
public Criteria within(Shape shape) {
Assert.notNull(shape, "Shape must not be null!");
criteria.put("$geoWithin", new GeoCommand(shape));
return this;
}
/**
* Creates a geospatial criterion using a {@literal $near} operation.
*
* @param point must not be {@literal null}
* @return this.
* @see <a href="https://docs.mongodb.com/manual/reference/operator/query/near/">MongoDB Query operator: $near</a>
*/
public Criteria near(Point point) {
Assert.notNull(point, "Point must not be null!");
criteria.put("$near", point);
return this;
}
/**
* Creates a geospatial criterion using a {@literal $nearSphere} operation. This is only available for Mongo 1.7 and
* higher.
*
* @param point must not be {@literal null}
* @return this.
* @see <a href="https://docs.mongodb.com/manual/reference/operator/query/nearSphere/">MongoDB Query operator:
* $nearSphere</a>
*/
public Criteria nearSphere(Point point) {
Assert.notNull(point, "Point must not be null!");
criteria.put("$nearSphere", point);
return this;
}
/**
* Creates criterion using {@code $geoIntersects} operator which matches intersections of the given {@code geoJson}
* structure and the documents one. Requires MongoDB 2.4 or better.
*
* @param geoJson must not be {@literal null}.
* @return this.
* @since 1.8
*/
@SuppressWarnings("rawtypes")
public Criteria intersects(GeoJson geoJson) {
Assert.notNull(geoJson, "GeoJson must not be null!");
criteria.put("$geoIntersects", geoJson);
return this;
}
/**
* Creates a geo-spatial criterion using a {@literal $maxDistance} operation, for use with $near
*
* @param maxDistance
* @return this.
* @see <a href="https://docs.mongodb.com/manual/reference/operator/query/maxDistance/">MongoDB Query operator:
* $maxDistance</a>
*/
public Criteria maxDistance(double maxDistance) {
if (createNearCriteriaForCommand("$near", "$maxDistance", maxDistance)
|| createNearCriteriaForCommand("$nearSphere", "$maxDistance", maxDistance)) {
return this;
}
criteria.put("$maxDistance", maxDistance);
return this;
}
/**
* Creates a geospatial criterion using a {@literal $minDistance} operation, for use with {@literal $near} or
* {@literal $nearSphere}.
*
* @param minDistance
* @return this.
* @since 1.7
*/
public Criteria minDistance(double minDistance) {
if (createNearCriteriaForCommand("$near", "$minDistance", minDistance)
|| createNearCriteriaForCommand("$nearSphere", "$minDistance", minDistance)) {
return this;
}
criteria.put("$minDistance", minDistance);
return this;
}
/**
* Creates a criterion using the {@literal $elemMatch} operator
*
* @param criteria must not be {@literal null}.
* @return this.
* @see <a href="https://docs.mongodb.com/manual/reference/operator/query/elemMatch/">MongoDB Query operator:
* $elemMatch</a>
*/
public Criteria elemMatch(Criteria criteria) {
this.criteria.put("$elemMatch", criteria.getCriteriaObject());
return this;
}
/**
* Creates a criterion using the given object as a pattern.
*
* @param sample must not be {@literal null}.
* @return this.
* @since 1.8
*/
public Criteria alike(Example<?> sample) {
if (StringUtils.hasText(this.getKey())) {
criteria.put("$example", sample);
return this;
}
Criteria exampleCriteria = new Criteria();
exampleCriteria.criteria.put("$example", sample);
return registerCriteriaChainElement(exampleCriteria);
}
/**
* Creates a criterion ({@code $jsonSchema}) matching documents against a given structure defined by the
* {@link MongoJsonSchema}. <br />
* <strong>NOTE:</strong> {@code $jsonSchema} cannot be used on field/property level but defines the whole document
* structure. Please use
* {@link org.springframework.data.mongodb.core.schema.MongoJsonSchema.MongoJsonSchemaBuilder#properties(JsonSchemaProperty...)}
* to specify nested fields or query them using the {@link #type(Type...) $type} operator.
*
* @param schema must not be {@literal null}.
* @return this
* @since 2.1
* @see <a href="https://docs.mongodb.com/manual/reference/operator/query/jsonSchema/">MongoDB Query operator:
* $jsonSchema</a>
*/
public Criteria andDocumentStructureMatches(MongoJsonSchema schema) {
Assert.notNull(schema, "Schema must not be null!");
Criteria schemaCriteria = new Criteria();
schemaCriteria.criteria.putAll(schema.toDocument());
return registerCriteriaChainElement(schemaCriteria);
}
/**
* Use {@link BitwiseCriteriaOperators} as gateway to create a criterion using one of the
* <a href="https://docs.mongodb.com/manual/reference/operator/query-bitwise/">bitwise operators</a> like
* {@code $bitsAllClear}.
*
* @return new instance of {@link BitwiseCriteriaOperators}. Never {@literal null}.
* @since 2.1
*/
public BitwiseCriteriaOperators bits() {
return new BitwiseCriteriaOperatorsImpl(this);
}
/**
* Creates a criteria using the {@code $or} operator for all of the provided criteria.
* <p>
* Note that MongoDB doesn't support an {@code $nor} operator to be wrapped in a {@code $not} operator.
*
* @throws IllegalArgumentException if this method follows a {@link #not()} call directly.
* @param criteria must not be {@literal null}.
* @return this.
*/
public Criteria orOperator(Criteria... criteria) {
Assert.notNull(criteria, "Criteria must not be null!");
return orOperator(Arrays.asList(criteria));
}
/**
* Creates a criteria using the {@code $or} operator for all of the provided criteria.
* <p>
* Note that MongoDB doesn't support an {@code $nor} operator to be wrapped in a {@code $not} operator.
*
* @throws IllegalArgumentException if this method follows a {@link #not()} call directly.
* @param criteria must not be {@literal null}.
* @return this.
* @since 3.2
*/
public Criteria orOperator(Collection<Criteria> criteria) {
Assert.notNull(criteria, "Criteria must not be null!");
BasicDBList bsonList = createCriteriaList(criteria);
return registerCriteriaChainElement(new Criteria("$or").is(bsonList));
}
/**
* Creates a criteria using the {@code $nor} operator for all of the provided criteria.
* <p>
* Note that MongoDB doesn't support an {@code $nor} operator to be wrapped in a {@code $not} operator.
*
* @throws IllegalArgumentException if this method follows a {@link #not()} call directly.
* @param criteria must not be {@literal null}.
* @return this.
*/
public Criteria norOperator(Criteria... criteria) {
Assert.notNull(criteria, "Criteria must not be null!");
return norOperator(Arrays.asList(criteria));
}
/**
* Creates a criteria using the {@code $nor} operator for all of the provided criteria.
* <p>
* Note that MongoDB doesn't support an {@code $nor} operator to be wrapped in a {@code $not} operator.
*
* @throws IllegalArgumentException if this method follows a {@link #not()} call directly.
* @param criteria must not be {@literal null}.
* @return this.
* @since 3.2
*/
public Criteria norOperator(Collection<Criteria> criteria) {
Assert.notNull(criteria, "Criteria must not be null!");
BasicDBList bsonList = createCriteriaList(criteria);
return registerCriteriaChainElement(new Criteria("$nor").is(bsonList));
}
/**
* Creates a criteria using the {@code $and} operator for all of the provided criteria.
* <p>
* Note that MongoDB doesn't support an {@code $and} operator to be wrapped in a {@code $not} operator.
*
* @throws IllegalArgumentException if this method follows a {@link #not()} call directly.
* @param criteria must not be {@literal null}.
* @return this.
*/
public Criteria andOperator(Criteria... criteria) {
Assert.notNull(criteria, "Criteria must not be null!");
return andOperator(Arrays.asList(criteria));
}
/**
* Creates a criteria using the {@code $and} operator for all of the provided criteria.
* <p>
* Note that MongoDB doesn't support an {@code $and} operator to be wrapped in a {@code $not} operator.
*
* @throws IllegalArgumentException if this method follows a {@link #not()} call directly.
* @param criteria must not be {@literal null}.
* @return this.
* @since 3.2
*/
public Criteria andOperator(Collection<Criteria> criteria) {
Assert.notNull(criteria, "Criteria must not be null!");
BasicDBList bsonList = createCriteriaList(criteria);
return registerCriteriaChainElement(new Criteria("$and").is(bsonList));
}
private Criteria registerCriteriaChainElement(Criteria criteria) {
if (lastOperatorWasNot()) {
throw new IllegalArgumentException(
"operator $not is not allowed around criteria chain element: " + criteria.getCriteriaObject());
} else {
criteriaChain.add(criteria);
}
return this;
}
/*
* @see org.springframework.data.mongodb.core.query.CriteriaDefinition#getKey()
*/
@Override
@Nullable
public String getKey() {
return this.key;
}
/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.query.CriteriaDefinition#getCriteriaObject()
*/
public Document getCriteriaObject() {
if (this.criteriaChain.size() == 1) {
return criteriaChain.get(0).getSingleCriteriaObject();
} else if (CollectionUtils.isEmpty(this.criteriaChain) && !CollectionUtils.isEmpty(this.criteria)) {
return getSingleCriteriaObject();
} else {
Document criteriaObject = new Document();
for (Criteria c : this.criteriaChain) {
Document document = c.getSingleCriteriaObject();
for (String k : document.keySet()) {
setValue(criteriaObject, k, document.get(k));
}
}
return criteriaObject;
}
}
protected Document getSingleCriteriaObject() {
Document document = new Document();
boolean not = false;
for (Entry<String, Object> entry : criteria.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (requiresGeoJsonFormat(value)) {
value = new Document("$geometry", value);
}
if (not) {
Document notDocument = new Document();
notDocument.put(key, value);
document.put("$not", notDocument);
not = false;
} else {
if ("$not".equals(key) && value == null) {
not = true;
} else {
document.put(key, value);
}
}
}
if (!StringUtils.hasText(this.key)) {
if (not) {
return new Document("$not", document);
}
return document;
}
Document queryCriteria = new Document();
if (!NOT_SET.equals(isValue)) {
queryCriteria.put(this.key, this.isValue);
queryCriteria.putAll(document);
} else {
queryCriteria.put(this.key, document);
}
return queryCriteria;
}
private BasicDBList createCriteriaList(Collection<Criteria> criteria) {
BasicDBList bsonList = new BasicDBList();
for (Criteria c : criteria) {
bsonList.add(c.getCriteriaObject());
}
return bsonList;
}
private void setValue(Document document, String key, Object value) {
Object existing = document.get(key);
if (existing == null) {
document.put(key, value);
} else {
throw new InvalidMongoDbApiUsageException("Due to limitations of the org.bson.Document, "
+ "you can't add a second '" + key + "' expression specified as '" + key + " : " + value + "'. "
+ "Criteria already contains '" + key + " : " + existing + "'.");
}
}
private boolean createNearCriteriaForCommand(String command, String operation, double maxDistance) {
if (!criteria.containsKey(command)) {
return false;
}
Object existingNearOperationValue = criteria.get(command);
if (existingNearOperationValue instanceof Document) {
((Document) existingNearOperationValue).put(operation, maxDistance);
return true;
} else if (existingNearOperationValue instanceof GeoJson) {
Document dbo = new Document("$geometry", existingNearOperationValue).append(operation, maxDistance);
criteria.put(command, dbo);
return true;
}
return false;
}
/*
* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || !getClass().equals(obj.getClass())) {
return false;
}
Criteria that = (Criteria) obj;
if (this.criteriaChain.size() != that.criteriaChain.size()) {
return false;
}
for (int i = 0; i < this.criteriaChain.size(); i++) {
Criteria left = this.criteriaChain.get(i);
Criteria right = that.criteriaChain.get(i);
if (!simpleCriteriaEquals(left, right)) {
return false;
}
}