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

280
Views
MongoDB. How to combine document with other documents values in aggregation framework?

I have documents like this:

[
  { id: 1, number: 10 },
  { id: 2, number: 11 },
  { id: 3, number: 12 }
]

How to get documents with combination of other values like example below using aggregation framework?

[
  { id: 1, number: 10, other_numbers: [11, 12] },
  { id: 2, number: 11, other_numbers: [10, 12] },
  { id: 3, number: 12, other_numbers: [10, 11] }
]
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

db.collection.aggregate([
  {
    $lookup: {
      "from": "collection",
      "let": {
        "number": "$number"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $ne: [ "$number", "$$number" ]
            }
          }
        }
      ],
      "as": "other_numbers"
    }
  },
  {
    $set: {
      "other_numbers": "$other_numbers.number"
    }
  }
])

mongoplayground


db.collection.aggregate([
  {
    "$group": {
      "_id": null,
      "number": {
        "$push": "$$ROOT"
      },
      "other_numbers": {
        "$push": "$$ROOT"
      }
    }
  },
  {
    "$unwind": "$number"
  },
  {
    "$set": {
      "other_numbers": {
        "$filter": {
          "input": "$other_numbers.number",
          "as": "i",
          "cond": {
            "$ne": [
              "$$i",
              "$number.number"
            ]
          }
        }
      },
      "number": "$number.number",
      "_id": "$number.id"
    }
  }
])

mongoplayground

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!