1
1
/*
2
- * Copyright 2010-2011 the original author or authors.
2
+ * Copyright 2010-2013 the original author or authors.
3
3
*
4
4
* Licensed under the Apache License, Version 2.0 (the "License");
5
5
* you may not use this file except in compliance with the License.
17
17
18
18
import java .util .HashMap ;
19
19
import java .util .Map ;
20
+ import java .util .Map .Entry ;
21
+
22
+ import org .springframework .util .Assert ;
20
23
21
24
import com .mongodb .BasicDBObject ;
22
25
import com .mongodb .DBObject ;
23
26
27
+ /**
28
+ * @author Thomas Risberg
29
+ * @author Oliver Gierke
30
+ * @author Patryk Wasik
31
+ */
24
32
public class Field {
25
33
26
- private Map <String , Integer > criteria = new HashMap <String , Integer >();
27
-
28
- private Map <String , Object > slices = new HashMap <String , Object >();
34
+ private final Map <String , Integer > criteria = new HashMap <String , Integer >();
35
+ private final Map <String , Object > slices = new HashMap <String , Object >();
36
+ private final Map <String , Criteria > elemMatchs = new HashMap <String , Criteria >();
37
+ private String postionKey ;
38
+ private int positionValue ;
29
39
30
40
public Field include (String key ) {
31
41
criteria .put (key , Integer .valueOf (1 ));
@@ -47,14 +57,50 @@ public Field slice(String key, int offset, int size) {
47
57
return this ;
48
58
}
49
59
60
+ public Field elemMatch (String key , Criteria elemMatchCriteria ) {
61
+ elemMatchs .put (key , elemMatchCriteria );
62
+ return this ;
63
+ }
64
+
65
+ /**
66
+ * The array field must appear in the query. Only one positional {@code $} operator can appear in the projection and
67
+ * only one array field can appear in the query.
68
+ *
69
+ * @param field query array field, must not be {@literal null} or empty.
70
+ * @param value
71
+ * @return
72
+ */
73
+ public Field position (String field , int value ) {
74
+
75
+ Assert .hasText (field , "Field must not be null or empty!" );
76
+
77
+ postionKey = field ;
78
+ positionValue = value ;
79
+
80
+ return this ;
81
+ }
82
+
50
83
public DBObject getFieldsObject () {
84
+
51
85
DBObject dbo = new BasicDBObject ();
86
+
52
87
for (String k : criteria .keySet ()) {
53
- dbo .put (k , ( criteria .get (k ) ));
88
+ dbo .put (k , criteria .get (k ));
54
89
}
90
+
55
91
for (String k : slices .keySet ()) {
56
- dbo .put (k , new BasicDBObject ("$slice" , ( slices .get (k ) )));
92
+ dbo .put (k , new BasicDBObject ("$slice" , slices .get (k )));
57
93
}
94
+
95
+ for (Entry <String , Criteria > entry : elemMatchs .entrySet ()) {
96
+ DBObject dbObject = new BasicDBObject ("$elemMatch" , entry .getValue ().getCriteriaObject ());
97
+ dbo .put (entry .getKey (), dbObject );
98
+ }
99
+
100
+ if (postionKey != null ) {
101
+ dbo .put (postionKey + ".$" , positionValue );
102
+ }
103
+
58
104
return dbo ;
59
105
}
60
106
}
0 commit comments