简体   繁体   中英

Mongodb 3.6 using multiple conditions on aggregation lookup

I have two collections in my MongoDb

  1. metricCollectionForms
  2. 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).

The pipeline form of lookup that would allow this is not available until MongoDB 4.2.

The best option in 3.6 is to follow the lookup with an $addFields stage with a $filter expression to remove the unwanted elements from the array.

The following should work for your example.

{
    $lookup: {
        from: "metric",
        localField: "formId",
        foreignField: "formula.formId",
        as: "metrics"
    }
},
{
    $match: {
       $and: {[
               "metrics.isApproved": true,
               "metrics.isActive": true
              ]}
    }
}

{ $match: {"metrics.isApproved": 'MA'}},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM