如何从MongoDB的BSON Document中提取List集合
解决MongoDB Document提取List集合返回null的问题
直接用document.get("years", List.class)返回null,是因为MongoDB Java驱动中,文档里的数组实际存储为BasicDBList(或驱动内部的列表实现),虽然它实现了List接口,但直接通过List.class作为类型参数调用get方法时,驱动无法正确识别匹配,导致返回null。这里给你几个简便的解决方法:
使用
getList方法(推荐)
MongoDB的Document类专门提供了getList方法来提取列表类型字段,它会自动处理内部类型转换:// 提取为Integer类型的List,确保类型安全 List<Integer> yearList = document.getList("years", Integer.class); // 如果担心字段不存在,可指定默认空列表 List<Integer> yearList = document.getList("years", Integer.class, new ArrayList<>());直接强转类型
如果不想用getList,也可以先获取字段值再强转为List(注意类型安全,避免ClassCastException):List<Integer> yearList = (List<Integer>) document.get("years");
额外注意:先确认你的projection参数中包含了"years"字段,如果投影时没指定包含该字段,返回的Document里根本没有years键,自然会返回null。
内容的提问来源于stack exchange,提问作者hinhnhumoi
相关产品推荐
相关产品推荐

