Home > database >  How can I get specific field value with array nested filter in MongoDB?
How can I get specific field value with array nested filter in MongoDB?

Time:05-27

After I filtered nested array values then I added "$project" query for selecting specific fields.

I want to get "new_yn" field values outside of the nested array but I only got id and nested array values.

How can I fix my Query? Would you give me some guides? (MongoDB version is 5.0.6 Community)

[Query]

db.collection.aggregate([
  {
    $match: {
      "new_yn": "Y",
      "port_info": {
        $elemMatch: {
          "port_code": "http_https"
        }
      }
    }
  },
  {
    $project: {
      port_info: {
        $filter: {
          input: "$port_info",
          as: "item",
          cond: {
            $eq: [
              "$$item.port_code",
              "http_https"
            ]
          }
        }
      }
    }
  },
  {
    "$project": {
      "_id": 1,
      "new_yn": 1,
      "port_info.ip_port": 1
    }
  }
])

[Mongo Playground]

https://mongoplayground.net/p/OXOaz8ct4KA

CodePudding user response:

This is because you haven't included it in the first $project stage.

Just add new_yn:1 to the first project stage and it will work.

db.collection.aggregate([
  {
    $match: {
      "new_yn": "Y",
      "port_info": {
        $elemMatch: {
          "port_code": "http_https"
        }
      }
    }
  },
  {
    $project: {
      new_yn: 1,
      port_info: {
        $filter: {
          input: "$port_info",
          as: "item",
          cond: {
            $eq: [
              "$$item.port_code",
              "http_https"
            ]
          }
        }
      }
    }
  },
  {
    "$project": {
      "_id": 1,
      "new_yn": 1,
      "port_info.ip_port": 1
    }
  }
])

As suggested by Bethlee, you can use $set as well, but it will bring all other fields from that document, which I believe you dont want.

  • Related