I'm quite new to MongoDB and its interaction with Java. I'm using this driver
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.4.2</version>
</dependency>
and I want to perform this aggregation query:
db.getCollection('COLLECTION').aggregate(
[
{"$match": {"val.elem.0001": {"$exists":true}}},
{"$project": {"FIELD_PATH": "$val.elem.0001"}},
{$group: {_id:{"FIELD": {"$literal": "0001"}},
"PATH": {"$addToSet": "$FIELD_PATH"}}}
]
);
The Java code I've written is the following, however I'm not sure if I correctly used the addToSet method:
AggregateIterable<Document> output = collection.aggregate(Arrays.asList(
new Document("$match", new Document("val.elem.0001",new Document("$exists",true))),
new Document("$project", new Document("FIELD_PATH","$val.elem.0001")),
new Document("$group", new Document("_id",new Document("FIELD", new Document("$literal", "0001"))
.append("PATH", Accumulators.addToSet("$PATH", "$FIELD_PATH"))))));
It is correct? Because I can't print the result on screen if I add the "append" part. The error that returns is
Can't find a codec for class com.mongodb.client.model.BsonField.
So, to summarize and make more readable and comprehensive what I've asked:
- Is the Java representation of the query correct?
- If so, why am I not able to print or access the result of the query?