|
Hi loikeseke@gmail.com,
I think the driver works as expected in the experiment you described. @BsonProperty simply allows an "alternative document key name when converting the POJO field to BSON", i.e., writing
@BsonProperty("subtest.subField")
|
public String subField;
|
means that the document field name "subtest.subField" is mapped to the POJO field name subField.
Executing
getCollection("test")
|
.find()
|
.projection(Projections.include("field", "subtest.subField"))
|
.cursor()
|
results in issuing the following find command:
{
|
"find": "test",
|
"filter": {},
|
"projection": {
|
"field": 1,
|
"subtest.subField": 1
|
}
|
}
|
which, in the experiment you described, produces a cursor with a single document
{
|
"_id" : ...,
|
"field" : "field",
|
"subtest" : {
|
"subField" : "subField"
|
}
|
}
|
This document does not have the "subtest.subField" field, instead it has the "subtest" field which value is a document with the "subField" field, consequently TestProjection.subField is null. In order to decode the document as TestProjection, one first needs to project it to have fields "field" and "subField". We can do this by using an aggregation expression, specifically an expression object. The find command we want is
{
|
"find": "test",
|
"filter": {},
|
"projection": {
|
"field": 1,
|
"subField": "$subtest.subField"
|
}
|
}
|
and can be issued by executing the following code
getCollection("test")
|
.find()
|
.projection(Projections.fields(
|
Projections.include("field"),
|
Projections.computed("subField", "$subtest.subField")))
|
.cursor()
|
With the above in mind, we can modify the experiment such that it decodes TestProjection as expected, and even still use @BsonProperty to display its purpose:
public static class TestProjection {
|
public String field;
|
@BsonProperty("subFieldWithDifferentName")
|
public String subField;
|
|
public String toString() {
|
return "TestProjection{" + "field='" + field + '\'' + ", subField='" + subField + '\'' + '}';
|
}
|
}
|
MongoCollection<TestProjection> projectedCollection = collection.withDocumentClass(TestProjection.class);
|
projectedCollection.find()
|
.projection(Projections.fields(
|
Projections.include("field"),
|
Projections.computed("subFieldWithDifferentName", "$subtest.subField")))
|
.cursor()
|
.forEachRemaining(System.out::println); // prints "TestProjection{field='field', subField='subField'}"
|
|