如何筛选查找结果 mongodb

How to filter results of an lookup mongodb

我是 mongodb 的新手。

我的查询给出了以下结果,我如何使用 mongodb 聚合过滤下面的结果以获得 expected_delivery_time:

[
   {
      "from":"Jeddah",
      "delivery_rule":[
         {
            "to":"Makkah",
            "expected_delivery_time":3
         },
         {
            "to":"Riyadh",
            "expected_delivery_time":2
         }
      ]
   },
   {
      "from":"Riyadh",
      "delivery_rule":[
         {
            "to":"Makkah",
            "expected_delivery_time":3
         },
         {
            "to":"Riyadh",
            "expected_delivery_time":1
         }
      ]
   }
]

下面是我的代码:

        $lookup:
          {
              from: "Setting",
              pipeline: [
                  {
                      $match:
                      {
                          $expr:
                              { $eq: ["$name", "delivery_rules"] }
                      }
                  }
              ],
              as: "delivery_rules"
          }
      },
      { "$match": { "$delivery_rules.value.from": "Jeddah" } },
      { "$match": { "$delivery_rules.value.to": "Riyadh" } },


我需要以下 MySQL 等效项的帮助

SELECT 'expected_delivery_time' WHERE from='Jeddah' AND to='Makkah'

基于$lookup阶段,我预计结果文件应该是:

[
  {
    "from": "Jeddah",
    "delivery_rules": [
      {
        "to": "Makkah",
        "expected_delivery_time": 3
      },
      {
        "to": "Riyadh",
        "expected_delivery_time": 2
      }
    ]
  },
  {
    "from": "Riyadh",
    "delivery_rules": [
      {
        "to": "Makkah",
        "expected_delivery_time": 3
      },
      {
        "to": "Riyadh",
        "expected_delivery_time": 1
      }
    ]
  }
]

delivery_rules(带有“s”,但您共享的文档是 delivery_rule

delivery_rules.value.fromdelivery_rules.value.to 都不存在。根据您的查询,您不应在 $match 阶段的字段中使用 $

  1. $lookup

  2. $match - 过滤器 fromdelivery_rules.to。将 2 $match 个阶段合并为 1 个。

  3. $project - 修饰输出文档。添加 expected_delivery_time 字段:

    3.1。 $getField - 从结果中获取 expected_delivery_time 字段 3.1.1.

    3.1.1。 $first - 从结果 3.1.1.1 数组中获取第一个值。

    3.1.1.1。 $filter - 过滤 to 的文档是 delivery_rules 数组中的“Makkah”。

db.collection.aggregate([
  /* Lookup stage */
  {
    "$match": {
      "from": "Jeddah",
      "delivery_rules.to": "Riyadh"
    }
  },
  {
    $project: {
      expected_delivery_time: {
        "$getField": {
          "field": "expected_delivery_time",
          "input": {
            $first: {
              $filter: {
                input: "$delivery_rules",
                cond: {
                  $eq: [
                    "$$this.to",
                    "Makkah"
                  ]
                }
              }
            }
          }
        }
      }
    }
  }
])

Sample Mongo Playground