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

119
Views
Mongodb Or query with two arrays

I am trying to perform an or query in MongoDB.

I have two array

firstNames = ['John', 'Tim','Joey']
lastNames = ['Alex', 'Smith', 'Mac']

I want to perform a query like

{$or: [{firstName: 'John', lastName: 'Alex'}, {firstName: 'John', lastName: 'Smith'}, {firstName: 'John', lastName: 'Mac'}, {firstName: 'Tim', lastName: 'Alex'} ... ]}

I tried

1.

Users.find({firstName: {$in: firstNames}, lastName: {$in: lastNames} })
Users.find({$or:[{firstName: {$in: firstNames}}, {lastName: {$in: lastNames} }]})

but this is wrong I guess. Can someone provide a better solution to this?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can create array of tuples using $zip. $match by $in to find expected records.

db.collection.aggregate([
  {
    "$addFields": {
      "names": {
        "$zip": {
          "inputs": [
            [
              "John",
              "Tim",
              "Joey"
            ],
            [
              "Alex",
              "Smith",
              "Mac"
            ]
          ]
        }
      }
    }
  },
  {
    "$match": {
      $expr: {
        "$in": [
          [
            "$firstName",
            "$lastName"
          ],
          "$names"
        ]
      }
    }
  },
  // cosmetics
  {
    "$project": {
      names: false
    }
  }
])

Here is the Mongo playground for your reference.

about 4 years ago · Juan Pablo Isaza 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!