如何在 MongoDB(特别是嵌套数组)中获得正确的查询结果?

How can I get a right query result in MongoDB (specially nested array)?

我猜想当我 运行 那个 MongoDB 查询时我只能得到过滤的 port_code 'http_https' 数据,但事实并非如此。选择所有数据。 如何修复我的查询?你能给我一些指导吗?

查询

{'port_info': {'$elemMatch': {'port_code': 'http_https'}}}

文档

[{
  "_id": {
    "$oid": "6267a966fe9fa7f41d42d255"
  },
  "new_yn": "Y",
  "port_info": [
    {
      "ip_port": "199.20.93.164:80",
      "use_yn": "Y",
      "comment": "",
      "port_code": "http_https",
      "uri_info": [
        {
          "uri": "199.20.93.164/",
          "status_code": 404
        }
      ]
    },
    {
      "ip_port": "199.20.93.164:5985",
      "use_yn": "Y",
      "comment": "",
      "port_code": "http_https",
      "uri_info": [
        {
          "uri": "199.20.93.164:5985",
          "status_code": 200
        }
      ]
    },
    {
      "ip_port": "199.20.93.164:21 ",
      "use_yn": "Y",
      "comment": "",
      "port_code": "ftp"
    }
  ]
}]

您可以使用过滤器:

db.collection.aggregate([
  {
    $project: {
      port_info: {
        $filter: {
          input: "$port_info",
          as: "item",
          cond: {$eq: ["$$item.port_code", "http_https"]}
        }
      }
    }
  }
])

如您所见this playground example