使用MongoDB Aggregate时如何保留Clients集合全部字段?
解决MongoDB聚合查询保留Clients全部字段的问题
你当前的聚合查询应该是通过$lookup关联了TypeClients集合,但后续阶段(比如$project)只指定了部分字段,导致Clients里的name、website等字段没被返回。要保留所有Clients原字段,同时带上关联的typeClient数据,给你两种实用的调整方式:
方法一:用$addFields保留全部原字段
这是最省心的方式,$addFields会自动保留所有现有字段,仅添加关联的typeClient数据:
db.Clients.aggregate([ { $lookup: { from: "TypeClients", localField: "idTypeClient", foreignField: "_id", as: "typeClient" } }, // 可选:如果typeClient是单个匹配结果,用$unwind把数组转成单个对象 { $unwind: "$typeClient" } ])
执行后,你会拿到Clients的所有原始字段,加上关联的typeClient数据。
方法二:保留原$project并引用整个文档
如果必须用$project过滤字段,别手动列所有字段,直接用$$ROOT引用整个Clients文档,再合并关联数据:
db.Clients.aggregate([ { $lookup: { from: "TypeClients", localField: "idTypeClient", foreignField: "_id", as: "typeClient" } }, { $project: { originalClient: "$$ROOT", typeClient: 1 } }, // 可选:展开原文档,避免嵌套在originalClient里 { $replaceRoot: { newRoot: { $mergeObjects: [ "$originalClient", { typeClient: "$typeClient" } ] } } } ])
这样处理后,原Clients的所有字段都会被保留,同时和typeClient数据合并到同一层级。
内容的提问来源于stack exchange,提问作者Jean François Manatane
相关产品推荐
相关产品推荐

