0

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.

1 Answer 1

1

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

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

Comments

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.