0

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

2
  • 1
    mongoplayground.net/p/ohSkR77mVAT Commented May 26, 2022 at 7:20
  • Wow. Thank you for your help again! @nimrodserok I'm newbie in MongoDB. I think "$set" is only used in insert or update queries. Commented May 26, 2022 at 7:21

1 Answer 1

1

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.

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

1 Comment

Thank you for helping me and attaching detail description about the query.

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.