Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

javascript - 如何在MongoDB中整理由$ lookup生成的内部数组(How to flat out inner array generated by $lookup in MongoDB)

I have 2 collections , Employees and Leads.(我有2个收藏集,员工和潜在顾客。)

Consider the query :(考虑查询:) const collections = Employees.aggregate( [ { $group: { _id: "$LeadId", total: { $sum: "$..." } } }, { $lookup: { from: "leads", localField: "_id", foreignField: "LeadId", as: "Joined" } }, { $unwind: "$Joined" }, { $sort: { total: -1 } } ], function(err, results) { if (err) { console.log(err); } // whatever } ); It produces the result :(它产生结果:) [0] _id: '6822ace7-00c4-4a3c-ac8e-56c7d715066c', [0] total: 0, [0] Joined: { [0] _id: 5de1bda51406d20017e69dbb, [0] Rooms: '3', [0] PhoneNumberMasque: '541234567', [0] supplier: 5de1bd861406d20017e69db2, [0] PackageId: 'Package_1457d5a7-2798-4ad6-99ca-a634b94e845d', [0] LeadId: '6822ace7-00c4-4a3c-ac8e-56c7d715066c', [0] __v: 0 [0] } [0] }, The rest of the result of lookup is inside the Joined array.(查找的其余结果位于Joined数组内部。) How can it be extracted out ?(如何将其提取出来?) EDIT With @Ashh suggestion the result is :(使用@Ashh建议进行编辑 ,结果为:) { [0] _id: '559c02a3-d933-41ff-b605-82a23ee94702', [0] Rooms: '2', [0] PhoneNumberMasque: '52123456', [0] supplier: 5de1bd861406d20017e69db2, [0] PackageId: 'Package_1457d5a7-2798-4ad6-99ca-a634b94e845d', [0] LeadId: '559c02a3-d933-41ff-b605-82a23ee94702', [0] PublishDate: 2019-11-30T02:53:57.000Z, [0] Duplicate: false, [0] Valid: true, [0] __v: 0, [0] total: 2, [0] Joined: { [0] _id: 5de1bda51406d20017e69dba, [0] Rooms: '2', [0] PhoneNumberMasque: '52123456', [0] supplier: 5de1bd861406d20017e69db2, [0] PackageId: 'Package_1457d5a7-2798-4ad6-99ca-a634b94e845d', [0] LeadId: '559c02a3-d933-41ff-b605-82a23ee94702', [0] PublishDate: 2019-11-30T02:53:57.000Z, [0] Duplicate: false, [0] Valid: true, [0] __v: 0 [0] } [0] },   ask by JAN translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use $replaceRoot with the Joined and the $$ROOT fields.(将$replaceRootJoined$$ROOT字段一起使用。)

It will bring you the Joined fields on the TOP level.(它将为您带来TOP级别的Joined字段。) { $replaceRoot: { newRoot: { $mergeObjects: ["$Joined", "$$ROOT"] }}}, { $project: { Joined: 0 }}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...