Uploaded image for project: 'Java Driver'
  1. Java Driver
  2. JAVA-4268

Projection didn't work for sub document using @BsonProperty

    • Type: Icon: Task Task
    • Resolution: Works as Designed
    • Priority: Icon: Unknown Unknown
    • None
    • Affects Version/s: None
    • Component/s: POJO
    • Labels:
    • Not Needed

      I have a Test object that have an embedded class SubTest.

       

      public class Test {
          public String field;
          public String unwanted;
          public SubTest subtest;
      
          public static class SubTest {
              public String subField;
              public String subUnwanted;
          }
      }
      

      And a projection class that I want to use with a projected query.

       

      public class TestProjection {
          public String field;
      
          @BsonProperty("subtest.subField")
          public String subField;
      }
      

      When I try to list all the document with a projection query that contains the fields "field" and "subtest.subField", the query succeed but the subField field is null.

      See the following example code snippet:

      MongoClient mongoClient = MongoClients.create();
      PojoCodecProvider pojoCodecProvider = PojoCodecProvider.builder().automatic(true).build();
      CodecRegistry pojoCodecRegistry = fromRegistries(getDefaultCodecRegistry(), fromProviders(pojoCodecProvider));
      MongoDatabase database = mongoClient.getDatabase("test").withCodecRegistry(pojoCodecRegistry);
      MongoCollection<Test> collection = database.getCollection("test", Test.class);
      
      Test test = new Test();
      test.field = "field";
      test.unwanted = "unwanted";
      Test.SubTest subTest = new Test.SubTest();
      subTest.subField = "subField";
      subTest.subUnwanted = "subUwanted";
      test.subtest = subTest;
      
      System.out.println("Inserting the element");
      collection.insertOne(test);
      
      System.out.println("Listing all elements");
      collection.find().cursor().forEachRemaining(System.out::println);
      
      System.out.println("Listing all elements with a projection");
      MongoCollection<TestProjection> projectedCollection = collection.withDocumentClass(TestProjection.class);
      projectedCollection.find()
              .projection(Projections.include("field", "subtest.subField"))
              .cursor()
              .forEachRemaining(System.out::println); ///here subtest.subField is null but should not be
      

       

            Assignee:
            valentin.kovalenko@mongodb.com Valentin Kavalenka
            Reporter:
            loikeseke@gmail.com Loïc MATHIEU
            Votes:
            0 Vote for this issue
            Watchers:
            4 Start watching this issue

              Created:
              Updated:
              Resolved: