我有2个收藏集,员工和潜在顾客。
考虑查询:
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
}
);
它产生结果:
[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] },
查找的其余结果位于
Joined
数组中。如何将其提取出来?
编辑
使用@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] },
最佳答案
将$replaceRoot
与Joined
和$$ROOT
字段一起使用。这将为您带来TOP级别的Joined
字段。
{ $replaceRoot: { newRoot: { $mergeObjects: ["$Joined", "$$ROOT"] }}},
{ $project: { Joined: 0 }}
关于javascript - 如何在MongoDB中整理$ lookup生成的内部数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59113377/