I have two collections in my MongoDb
- metricCollectionForms
- metric
A metricCollectionForms
document looks something like this
{
"_id": ObjectId("5ea25f38afd94f0008d4e6f2"),
"approverId": "f08ba2aa-4597-41f0-9e6c-cebf1715ba30",
"formName": "Test Form",
"formId": "d56209a1-4df0-48de-b6cf-d1ee50200936",
}
I have skipped few attributes from the document above because they are not relevant to this question.
As for the metric
a typical document looks like this
{
"_id": ObjectId("5ea27955bae4900008d996ba"),
"name": "Test Metric",
"type": "INTERNAL",
"formula": [
{
"type": "FORM_FIELD",
"formId": "d56209a1-4df0-48de-b6cf-d1ee50200936",
"formFieldId": "dca2bacf-2cbd-480d-8289-6f3050b635fb"
},
{...}, {...}
],
"formulaLabel": "monthly_production",
"createdBy": "f08ba2aa-4597-41f0-9e6c-cebf1715ba30",
"isApproved": true,
"isActive": false
}
You will notice that the formId
value from metricCollectionForms
is being referenced in the formula array formId
field of the metric
document.
So one metric can use many forms within its formula array of object.
I am trying to get list of forms and within that list return the array of metric name where
metric.formula.formId = formId (of the form) AND metric.isActive = true AND metric.isApproved = true
So far my aggregate query looks something like this:
{
$lookup: {
from: "metric",
localField: "formId",
foreignField: "formula.formId",
as: "metrics"
}
},
{
$addFields: {
metrics: "$metrics.name"
}
}
Now it does return me an array of all metric names but I do not know how I can apply the isApproved and isActive true conditions on the $lookup.
I tried doing $pipeline / $match etc but nothing seems to work. Also the solution should be compatible to Mongo 3.6 as I am using this within AWS DocumentDb (which only supports 3.6).