springboot mongodb Document插入时内嵌数组字段里的对象如何自动填充

问题场景

springboot项目中操作mongodb对Document进行插入操作,对其数组字段对象中的元素使用自动填充

测试Document对象

@Data
@Document
public class TestDocument {

    @MongoId
    private String id;

    private List<TestField> fields;

}
@Data
public class TestField {

    @MongoId
    private String id;

    private String name;

    @CreatedDate
    private LocalDateTime time;
}

问题描述:

        TestDocument testDocument = new TestDocument();

        TestField testField = new TestField();
        testField.setName("测试");

        testDocument.setFields(Collections.singletonList(testField));
        System.out.println(mongoTemplate.save(testDocument));

插入操作返回的数据未能自动填充

MongoDB存储数据

{
    "_id": "6414466c347e397d7d393b0e",
    "fields": [
        {
            "name": "测试"
        }
    ]
}

提问

Document内嵌List字段中的元素是否能使用自动填充?需要怎么配置内嵌List字段中的元素才能使用自动填充?

参考GPT和自己的思路:

是的,Document内嵌List字段中的元素可以使用自动填充。在上述代码中,TestField对象中使用了@CreatedDate注解,这是一个MongoDB在插入操作时自动填充创建时间的注解。但是在List中的元素要使用这个注解需要一些额外的配置。

需要在TestField类上添加@Document注解,并在其中指定“collection”属性的值为“testdocument.fields”,表示这个类以内嵌文档的形式存在于TestDocument的fields列表中。并且在TestDocument类中的fields字段上添加@Field注解,指定“targetType”属性为TestField.class,表示这个字段需要转成TestField类型的对象才能使用@CreatedDate注解。

修改后的代码如下所示:

@Data
@Document
public class TestDocument {

    @MongoId
    private String id;

    @Field(targetType = TestField.class)
    private List<TestField> fields;

}


@Data
@Document(collection = "testdocument.fields")
public class TestField {

    @MongoId
    private String id;

    private String name;

    @CreatedDate
    private LocalDateTime time;
}

这样配置之后,在进行Document对象插入操作时,内嵌List字段中的元素就会自动填充创建时间了。