MongoDB如何展开嵌套JSON并按规则重命名字段?
解决方案
1. MongoDB原生聚合查询
直接使用$project聚合阶段完成字段重命名与映射,不需要修改原有数据,查询直接返回符合要求的结构:
// 替换yourCollectionName为实际集合名 db.yourCollectionName.aggregate([ { $project: { _id: 0, // 不返回原生_id字段 slot_id: "$_id.uuid", // 映射_id.uuid到slot_id id: "$_id.sectionId", // 映射_id.sectionId到id slot_name: "$name" // 映射name到slot_name } } ])
2. Java端实现
基于Spring Data MongoDB(MongoTemplate)
import org.springframework.data.mongodb.core.aggregation.Aggregation; import static org.springframework.data.mongodb.core.aggregation.Aggregation.*; // 构造聚合规则 Aggregation aggregation = newAggregation( project() .and("_id.uuid").as("slot_id") .and("_id.sectionId").as("id") .and("name").as("slot_name") .andExclude("_id") ); // 执行查询,OutputDTO为自定义的结果接收实体类 List<OutputDTO> resultList = mongoTemplate.aggregate(aggregation, "你的实际集合名", OutputDTO.class).getMappedResults();
基于MongoDB官方Java驱动
import com.mongodb.client.MongoCollection; import com.mongodb.client.model.Aggregates; import com.mongodb.client.model.Projections; import org.bson.Document; import java.util.ArrayList; import java.util.Arrays; // 执行查询 List<Document> resultList = yourCollection.aggregate(Arrays.asList( Aggregates.project(Projections.fields( Projections.excludeId(), Projections.computed("slot_id", "$_id.uuid"), Projections.computed("id", "$_id.sectionId"), Projections.computed("slot_name", "$name") )) )).into(new ArrayList<>());
该方案直接在MongoDB服务端完成字段转换,无需在Java层遍历处理文档,代码简洁且执行效率更高。
内容的提问来源于stack exchange,提问作者nkhcode
相关产品推荐
相关产品推荐

