如何修改MongoDB查询返回的数据结构?
修改MongoDB查询返回数据结构的两种方法
你可以通过以下两种方式将查询结果转换成目标格式:
方法一:MongoDB聚合管道处理(数据库层面转换)
直接在查询阶段用聚合管道重构数据结构,减少后端代码处理量:
ProfileModel.aggregate([ // 筛选目标数据,和原find条件一致 { $match: { _id: { $in: [ '63a0488c88723874c1fb3fbf', '63a04894d4bdd0a191b69573' ] } } }, // 重构每个文档的结构 { $project: { _id: 0, // 去掉原文档的_id字段 type: { $literal: "User" }, // 固定type字段值为"User" attributes: { name: "$name", image: "$image" // 有其他字段直接在这里添加即可 } } }, // 将所有文档打包到data数组中 { $group: { _id: null, data: { $push: "$$ROOT" } } }, // 去掉分组产生的_id字段 { $project: { _id: 0 } } ])
如果原文档字段较多,不想逐个列举,可用$mergeObjects简化attributes生成:
{ $project: { _id: 0, type: "User", attributes: { $mergeObjects: [$$ROOT, { _id: "$$REMOVE" }] } } }
方法二:后端代码层面转换
先获取原始数据,再通过JavaScript数组方法转换结构:
ProfileModel.find({ _id: { $in: [ '63a0488c88723874c1fb3fbf', '63a04894d4bdd0a191b69573' ] } }) .lean() // 返回普通JavaScript对象,提升处理性能 .then(originalData => { // 转换数据结构 const result = { data: originalData.map(item => ({ type: "User", attributes: { name: item.name, image: item.image } })) }; // 这里可直接使用转换后的result }) .catch(error => { // 处理查询错误 });
内容的提问来源于stack exchange,提问作者Afdal
相关产品推荐
相关产品推荐

