Multiple lookup with same collection MongoDb Aggregate
xxxxxxxxxx
db.collection2.aggregate([
{
$lookup: {
from: "collection1",
let: {
firstUser: "$user1",
secondUser: "$user2"
},
pipeline: [
{
$match: {
$expr: {
$and: [
{
$eq: [
"$user1",
"$$firstUser"
]
},
{
$eq: [
"$user2",
"$$secondUser"
]
}
]
}
}
}
],
as: "result"
}
},
{
$replaceRoot: {
newRoot: {
$mergeObjects:[
{
$arrayElemAt: [
"$result",
0
]
},
{
percent1: "$$ROOT.percent1"
}
]
}
}
}
]
)
xxxxxxxxxx
db.collection2.aggregate([
{
$lookup: {
from: "collection1",
let: {
firstUser: "$user1",
secondUser: "$user2"
},
pipeline: [
{
$match: {
$expr: {
$and: [
{
$eq: [
"$user1",
"$$firstUser"
]
},
{
$eq: [
"$user2",
"$$secondUser"
]
}
]
}
}
}
],
as: "result"
}
},
{
$replaceRoot: {
newRoot: {
$mergeObjects:[
{
$arrayElemAt: [
"$result",
0
]
},
{
percent1: "$$ROOT.percent1"
}
]
}
}
}
]
)
xxxxxxxxxx
db.getCollection('_project').aggregate([
{$lookup:{from: "_build",localField: "_id",foreignField: "ProjectId",as:"result"}},
{$unwind:"$result"},
{$project:{_id:0,ProjectId:"$_id",BuildId:"$result._id"}},
{$lookup:{from:"_build.detail",localField:"BuildId",foreignField:"BuildId",as:"resultS2"}},
{$unwind:"$resultS2"},
{$group:{
_id:{ProjectId:"$ProjectId", BuildId:"$BuildId",campaignName:"$resultS2.Data.Campaign Name",adSet:"$resultS2.Data.Ad Set Name"},
uniqueAdNames:{$addToSet:"$resultS2.Data.Ad Name"}
}
},
{$addFields:{uniqueAdsCount:{$size:"$uniqueAdNames" }}},
{$group :{
_id:{ProjectId:"$_id.ProjectId",BuildId:"$_id.BuildId",campaignName:"$_id.campaignName"},
uniqueAdNames:{$first:"$uniqueAdNames"},
uniqueAdsCount:{$first:"$uniqueAdsCount"},
uniqueAdSets:{$addToSet:"$_id.adSet"}
}
},
{$addFields:{uniqueAdsetCount:{$size:"$uniqueAdSets"}}},
{$group:{
_id:{ProjectId:"$_id.ProjectId",BuildId:"$_id.BuildId"},
uniqueAdNames:{$first:"$uniqueAdNames"},
uniqueAdsCount:{$first:"$uniqueAdsCount"},
uniqueAdSetNames:{$first:"$uniqueAdSets"},
uniqueAdsetCount:{$first:"$uniqueAdsetCount"},
uniqueCampaignNames:{$addToSet:"$_id.campaignName"}
}
},
{$addFields:{uniqueCampaignCount:{$size : "$uniqueCampaignNames"}}}
])