簡體   English   中英

Mongodb 3.6 在聚合查找中使用多個條件

[英]Mongodb 3.6 using multiple conditions on aggregation lookup

我的MongoDb里面有兩個collections

  1. metricCollectionForms
  2. 公制

metricCollectionForms文檔看起來像這樣

{
    "_id": ObjectId("5ea25f38afd94f0008d4e6f2"),
    "approverId": "f08ba2aa-4597-41f0-9e6c-cebf1715ba30",
    "formName": "Test Form",
    "formId": "d56209a1-4df0-48de-b6cf-d1ee50200936",
}

我從上面的文檔中跳過了幾個屬性,因為它們與這個問題無關。

至於metric ,一個典型的文件看起來像這樣

{
    "_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
}

您會注意到metric文檔的公式數組formId字段中引用了metricCollectionForms中的formId值。

因此,一個指標可以在其 object 的公式數組中使用多個 forms。

我正在嘗試獲取 forms 的列表,並在該列表中返回指標名稱數組,其中

metric.formula.formId = formId(表單的)AND metric.isActive = true AND metric.isApproved = true

到目前為止,我的聚合查詢看起來像這樣:

{
    $lookup: {
        from: "metric",
        localField: "formId",
        foreignField: "formula.formId",
        as: "metrics"
    }
},
{
    $addFields: {
        metrics: "$metrics.name"
    }
}

現在它確實返回了一個包含所有指標名稱的數組,但我不知道如何在 $lookup 上應用 isApproved 和 isActive true 條件。

我嘗試做 $pipeline / $match 等,但似乎沒有任何效果。 此外,該解決方案應該與 Mongo 3.6 兼容,因為我在 AWS DocumentDb(僅支持 3.6)中使用它。

直到 MongoDB 4.2 之后,才可以使用管道形式的查找。

3.6 中的最佳選擇是在查找之后使用帶有$filter表達式的$addFields階段從數組中刪除不需要的元素。

以下內容適用於您的示例。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM