MongoDB投影阶段添加自定义对象的实现方法咨询
问题描述
我的数据库中有如下文档:
[ { _id: 12, name: "access", mobileNo: 9153438340 }, { _id: 13, name: "Apple", mobileNo: 9153438343 }, { _id: 14, name: "Dell", mobileNo: 9153438344 } ]
我希望在聚合结果里添加另一个对象:
{ _id: 15, name: "Skype", mobileNo: 9153438345 }
最终要得到的合并结果是:
[ { _id: 12, name: "access", mobileNo: 9153438340 }, { _id: 13, name: "Apple", mobileNo: 9153438343 }, { _id: 14, name: "Dell", mobileNo: 9153438344 }, { _id: 15, name: "Skype", mobileNo: 9153438345 } ]
我尝试了下面的聚合查询,但没得到预期效果,请问还有其他实现方法吗?
db.collection.aggregate([ { $project: { _id: 1, name: 1, mobileNo: 1 // Include other fields from the existing documents as needed } }, { $project: { combinedResults: { $concatArrays: [ [ { _id: 15, name: "test", mobileNo: 9553438343 // Add other fields to the new object as needed } ], "$$ROOT" // Include the existing documents ] } } }, { $unwind: "$combinedResults" // Unwind the array to get separate documents } ]);
解决方法
你的原有查询问题出在$concatArrays里用了$$ROOT——$$ROOT代表当前单个文档对象,不是数组,无法和新文档的数组拼接,自然得不到正确结果。下面提供几种可行的实现方式:
方法一:使用$unionWith(MongoDB 4.4及以上版本)
这是最简洁的方式,直接将现有集合的文档和自定义的新文档集合做并集:
db.collection.aggregate([ { $unionWith: { coll: { $documents: [ { _id: 15, name: "Skype", mobileNo: 9153438345 } ] } } } ])
方法二:先聚合为数组再拼接
先把所有现有文档聚合成一个数组,再和新文档的数组拼接,最后展开成单个文档:
db.collection.aggregate([ // 将所有文档合并到一个数组中 { $group: { _id: null, docs: { $push: "$$ROOT" } } }, // 拼接新文档到数组 { $project: { combined: { $concatArrays: [ "$docs", [{ _id: 15, name: "Skype", mobileNo: 9153438345 }] ] } } }, // 展开数组为单个文档 { $unwind: "$combined" }, // 替换根节点得到最终文档结构 { $replaceRoot: { newRoot: "$combined" } } ])
方法三:低版本兼容方案(MongoDB 3.2+)
如果你的MongoDB版本低于4.4,可以用$addToSet替代$push(效果一致,仅多了去重逻辑,这里不影响结果),步骤和方法二类似:
db.collection.aggregate([ { $group: { _id: null, docs: { $addToSet: "$$ROOT" } } }, { $project: { combined: { $concatArrays: [ "$docs", [{ _id: 15, name: "Skype", mobileNo: 9153438345 }] ] } } }, { $unwind: "$combined" }, { $replaceRoot: { newRoot: "$combined" } } ])
内容的提问来源于stack exchange,提问作者ram12393
相关产品推荐
相关产品推荐

