MongoDB -如何过滤查找结果

dced5bon  于 2022-12-03  发布在  Go
关注(0)|答案(1)|浏览(157)

我是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'
igetnqfo

igetnqfo1#

基于$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-过滤delivery_rules数组中to为“麦加”的文档。
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

相关问题