Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

175
Views
find customers in zip code using mongodb aggrigation

I have 2 mongodb documents shop and customer

shop documents are like below

{
 id: 1,
 zipcodes:[ 
  '12345',
  '11111',
 ]
}

{
 id:2,
 zipcodes:[
  '45678',
 ]
}

customer documents are like below

{
 id:20,
 name: 'First Last',
 address: [
  {
   id:110,
   address: 'address line1',
   zipcode: '12345',
  },
  {
   id:111,
   address: 'address new',
   zipcode: '45678',
  }
 ]
},
{
 id:25,
 name: 'First Last2',
 address: [
  {
   id:113,
   address: 'address new',
   zipcode: '45678',
  },
 ]
},
{
 id:29,
 name: 'First Name',
 address: [
  {
   id:119,
   address: 'address liner',
   zipcode: '11111',
  },
  {
   id:120,
   address: 'address new2',
   zipcode: '12345',
  }
 ]
},

expected output. I need to get customers in same zip code

[
 {
  zipcode: 12345,
  customers:[
   {id:20},
   {id:29},
  ]
 },
 {
  zipcode: 11111,
  customers:[
   {id:29},
  ]
 },
 {
  zipcode: 45678,
  customers:[
   {id:25},
  ]
 },
]

I tried to solve this using mongodb aggregation framework but no luck so far. I have no idea how to match object elements in a array. thanks in advance. please help.

edited- added expected output

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

  1. $unwind - Deconstruct zipcodes array to multiple documents.

  2. $lookup - Join shops with customers collection.

    2.1. $match - shops' zipcode is within address.zipcode from customers.

    2.2. $project - Decorate the output documents for customers array.

  3. $project - Decorate the output documents.

db.shops.aggregate([
  {
    $unwind: "$zipcodes"
  },
  {
    $lookup: {
      from: "customers",
      let: {
        zipcodes: "$zipcodes"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              "$in": [
                "$$zipcodes",
                "$address.zipcode"
              ]
            }
          }
        },
        {
          $project: {
            _id: 0,
            id: 1
          }
        }
      ],
      as: "customers"
    }
  },
  {
    $project: {
      _id: 0,
      zipcodes: 1,
      customers: 1
    }
  }
])

Sample Mongo Playground

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!