Skip to content

Commit 44135a6

Browse files
committed
Throw an error if merge tries to join on duplicate fields
1 parent 84f5d1c commit 44135a6

File tree

2 files changed

+14
-8
lines changed

2 files changed

+14
-8
lines changed

core/src/main/java/de/bwaldvogel/mongo/backend/aggregation/stage/MergeStage.java

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -118,14 +118,17 @@ private Set<String> getJoinFields(Document paramsDocument) {
118118
if (collection.isEmpty()) {
119119
throw new MongoServerError(51187, "If explicitly specifying $merge 'on', must include at least one field");
120120
}
121-
return collection.stream()
122-
.map(value -> {
123-
if (!(value instanceof String)) {
124-
throw new MongoServerError(51134, "$merge 'on' array elements must be strings, but found " + Utils.describeType(value));
125-
}
126-
return (String) value;
127-
})
128-
.collect(Collectors.toCollection(LinkedHashSet::new));
121+
Set<String> joinFields = new LinkedHashSet<>();
122+
for (Object value : collection) {
123+
if (!(value instanceof String)) {
124+
throw new MongoServerError(51134, "$merge 'on' array elements must be strings, but found " + Utils.describeType(value));
125+
}
126+
String joinField = (String) value;
127+
if (!joinFields.add(joinField)) {
128+
throw new MongoServerError(31465, "Found a duplicate field '" + joinField + "'");
129+
}
130+
}
131+
return joinFields;
129132
} else {
130133
throw new MongoServerError(51186, "$merge 'on' field must be either a string or an array of strings, but found " + Utils.describeType(on));
131134
}

test-common/src/main/java/de/bwaldvogel/mongo/backend/AbstractAggregationTest.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2488,6 +2488,9 @@ private static Stream<Arguments> aggregateWithMerge_illegalParametersArguments()
24882488
Arguments.of("$merge: { into: 'abc', on: [1, 2, 3] }", MongoCommandException.class,
24892489
"Command failed with error 51134 (Location51134): '$merge 'on' array elements must be strings, but found int'"),
24902490

2491+
Arguments.of("$merge: { into: 'abc', on: ['a', 'b', 'a'] }", MongoCommandException.class,
2492+
"Command failed with error 31465 (Location31465): 'Found a duplicate field 'a''"),
2493+
24912494
Arguments.of("$merge: { into: 'abc', on: [] }", MongoCommandException.class,
24922495
"Command failed with error 51187 (Location51187): 'If explicitly specifying $merge 'on', must include at least one field'"),
24932496

0 commit comments

Comments
 (0)