0

I guessed when I run that MongoDB Query then I can get only filtered port_code 'http_https' data but it wasn't. All data is selected. How can I fix my Query? Would you give me some guides?

Query

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

Documents

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

1 Answer 1

1

You can use a filter:

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

As you can see on this playground example

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your help. How can I make those queries? I thought that project just for using get fields.
I don't understand the question "How can I make those queries?" Can you clarify? $project is a way to format your documents. $filter is a way to format them.
Thank you for the explanation. I mean.. I'm struggling to make query in MongoDB. That's why wrote that sentence.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.