我正试图让一个聚合与猫鼬一起工作,但我遇到了几个问题,
来自用户模型的文档
{
"_id": {
"$oid": "630273bbe0f3f82d85b149bd"
},
"password": "$2b$12$2f04ijl0fDVHUgBF3rZi.eKfNYkzHZShHNPKfiDEu2NXEXhb.2O",
"name": "name1",
"tel": "+33612345678"
}
潜在客户模型文档
{
"_id": {
"$oid": "6319e54c8cc8b7a5521ad266"
},
"name": "name2",
"tel": "+33712345678"
}
我有另一个模型Bookings
,其中ref
是Users
或Leads
模型,我想与之进行聚合,
有一个预订文件的例子:
{
"_id": {
"$oid": "6310a86c6303d0987fe6fac4"
},
"date": {
"$date": "2022-09-01T14:36:12Z"
},
"user": {
"$oid": "630273bbe0f3f82d85b149bd"
},
"ref": "User"
}
这是我的聚合:
const leads = await this.bookingModel.aggregate([
{
$group: {
_id: {
user: '$user'
}
}
},
{
$lookup: {
from: 'users',
localField: '_id.user',
foreignField: '_id',
as: 'leadUser',
pipeline: [
{
$project: {
name: 1,
tel: 1
}
}
]
}
},
{ $unwind: { path: '$leadUser', preserveNullAndEmptyArrays: true } },
{
$lookup: {
from: 'leads',
localField: '_id.user',
foreignField: '_id',
as: 'lead',
pipeline: [
{
$project: {
name: 1,
tel: 1
}
}
]
}
},
{ $unwind: { path: '$lead', preserveNullAndEmptyArrays: true } }
])
,有几个问题我想解决
首先,我不能在查找as
时设置相同的密钥,如何避免放置lead
和leadUser
并放置相同的密钥
此外,如何通过tel
来$group
以避免重复文档,tel
在两个模型中,现在我只与用户分组,但我不希望用户和Lead有相同的电话。
编辑:有操场https://mongoplayground.net/p/TyYvasdyz_O
我想要铅和铅用户的相同密钥,并按电话分组以删除重复的
非常感谢!
如果我理解正确,你想要这样的东西:
- 在
$lookup
s之后,不要执行`$unvent,而是连接数组并只保留第一项 - 按
$tel
分组以保持其唯一性
db.bookings.aggregate([
{$group: {_id: {user: "$user"}}},
{$lookup: {
from: "users",
localField: "_id.user",
foreignField: "_id",
as: "leadUser",
pipeline: [{$project: {name: 1, tel: 1}}]
}
},
{$lookup: {
from: "leads",
localField: "_id.user",
foreignField: "_id",
as: "lead",
pipeline: [{$project: {name: 1, tel: 1}}]
}
},
{$project: {lead: {$first: {$concatArrays: ["$lead", "$leadUser"]}}}},
{$group: {_id: "$lead.tel", lead: {$first: "$lead"}, user: {$first: "$_id.user"}}},
{$project: {_id: {user: "$user"}, lead: 1}}
])
看看它是如何在操场上工作的例子