I have two tables vendor and vendorOrg table. I needs to return the list based on vendorOrg table criteria wise and category -wise
const vendors = [{
"name" : "Alfred",
"location" : "FH",
"vendorOrgId" : "1"
},
{
"name" : "Alfred",
"location" : "ADH",
"vendorOrgId" : "2"
},
{
"name" : "Alfred",
"location" : "AFF",
"vendorOrgId" : "41"
}]
const vendorOrg = [
{
"orgName" : "star super market",
"vendorOrgId" : "1",
"category" : "grocery",
"status" : "active"
},
{
"orgName" : "L.f super market",
"vendorOrgId" : "41",
"category" : "grocery",
"status" : "active"
},
{
"orgName" : "Fresh mart",
"vendorOrgId" : "2",
"category" : "Milk",
"status" : "active"
}
]
find conditions below, 1.vendor's table vendorOrgId must be same as vendorOrg's table id. 2. vendorOrg table status should active. if above conditions are true, the i needs a vendor list category-wise, based on vendorOrg's table category.
{
"grocery": [{
"name": "Alfred",
"location": "FH",
"vendorOrgId": "1"
},
{
"name": "Alfred",
"location": "AFF",
"vendorOrgId": "41"
}
],
"milk": [{
"name": "Alfred",
"location": "ADH",
"vendorOrgId": "2"
}]
}
Is this possible to do with mongoose. Thanks!
$lookup with vendorLog collection and pass vendorOrgId to lookup pipeline$match required conditions$project to show required fields$unwind deconstruct org array$group by org category and construct array of vendors$group by null and construct array in key-value format$arrayToObject convert key-value pair array to object$replaceRoot to replace object to rootdb.vendors.aggregate([
{
$lookup: {
from: "vendorOrg",
let: { vendorOrgId: "$vendorOrgId" },
pipeline: [
{
$match: {
$expr: { $eq: ["$$vendorOrgId", "$vendorOrgId"] },
status: "active"
}
},
{ $project: { _id: 1, category: 1 } }
],
as: "org"
}
},
{ $unwind: "$org" },
{
$group: {
_id: "$org.category",
vendors: {
$push: {
name: "$name",
location: "$location",
vendorOrgId: "$vendorOrgId"
}
}
}
},
{
$group: {
_id: null,
vendors: { $push: { k: "$_id", v: "$vendors" } }
}
},
{ $replaceRoot: { newRoot: { $arrayToObject: "$vendors" } } }
])