MongoDB与Java:CodecRegistry仅返回POJO的ID字段,如何获取全部字段?
问题
我在Java Spring项目中使用以下代码创建Mongo客户端:
CodecRegistry pojoCodecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), fromProviders(PojoCodecProvider.builder().register(Person.class).automatic(true).build())); MongoClientSettings settings = MongoClientSettings.builder() .codecRegistry(pojoCodecRegistry) .applyConnectionString(new ConnectionString("myConnectionStrng")) .build(); MongoClient mongoClient = MongoClients.create(settings); MongoDatabase database = mongoClient.getDatabase("person").withCodecRegistry(pojoCodecRegistry); MongoCollection<Person> collection = database.getCollection("personCollection", Person.class).withCodecRegistry(pojoCodecRegistry);
我的Kotlin POJO定义如下:
@JsonInclude(JsonInclude.Include.NON_NULL) class Person { @JsonProperty("_id") var personID: String? = null @JsonProperty("name") var type: String? = null @JsonProperty("age") var age: Int? = null }
能获取到响应,但结果不符合预期,仅返回ID字段:
{ "persons": [ { "ID": "personId1" }, { "ID": "personId2" }, { "ID": "personId3" } ] }
每个Person对象仅显示ID字段,而非POJO中定义的所有字段。请问我遗漏了什么?是否需要为POJO定义自定义Codec?我是首次使用该Mongo库,不太确定。
解决方案
问题核心是你混用了Jackson注解与MongoDB原生POJO Codec:MongoDB的PojoCodecProvider默认不识别Jackson的@JsonProperty注解,只会按字段名映射MongoDB文档的键,导致除ID外的字段无法正确映射。
你不需要自定义Codec,只需做以下调整:
- 将Jackson的
@JsonProperty替换为MongoDB的@BsonProperty注解,用来指定MongoDB文档中的对应字段名。 - 确保Kotlin类保留无参构造函数(当前代码已满足,但后续修改时注意不要移除)。
修改后的Kotlin POJO:
import org.bson.codecs.pojo.annotations.BsonProperty import com.fasterxml.jackson.annotation.JsonInclude @JsonInclude(JsonInclude.Include.NON_NULL) class Person { @BsonProperty("_id") var personID: String? = null @BsonProperty("name") var type: String? = null @BsonProperty("age") var age: Int? = null }
额外检查:确认MongoDB文档中的字段名与@BsonProperty指定的完全一致(比如文档中确实存在name和age字段),避免因字段名不匹配导致映射失败。
内容的提问来源于stack exchange,提问作者java12399900
相关产品推荐
相关产品推荐

