Stack Exchange
Filter twice based on input from first filter's output in MongoDB
Given a collection like below, when input is "Ross", I want all records whose zipcode matches with Ross.
Input is not zipcode but name.
[
  {
    name : "Ross",
    zipcode : "12345" 
  },
  {
    name : "joey",
    zipcode : "12345" 
  },
  {
    name : "chandler",
    zipcode : "22457" 
  },
  {
    name : "monica",
    zipcode : "22457" 
  },
  {
    name : "phoebe",
    zipcode : "32457" 
  },
  {
    name : "rachel",
    zipcode : "32457" 
  }
]

In this case, when I get "Ross" as input, the output should be
[
  {
    name : "Ross",
    zipcode : "12345" 
  },
  {
    name : "joey",
    zipcode : "12345" 
  }
]

I have tried looking into mongo-aggregation, but I did not come across a solution that meets my use-case.
Kindly point me in the right direction.

You can try this one:
db.collection.aggregate([
   {
      $lookup: {
         from: "collection",
         localField: "zipcode",
         foreignField: "zipcode",
         as: "zipcodes"
      }
   },
   {
      $match: {
         $or: [
            { name: "Ross" },
            { "zipcodes.name": "Ross" },
         ]
      }
   },
   { $unset: "zipcodes" }
])

Mongo Playground
