ASHafizullah
ASHafizullah

Reputation: 729

How to aggregate mongoose deep collection? (Filter Data)

I have a question about how to aggregate mongoose deep collection, for example i have 3 collections:

  1. Specialization job
[
  {
   "id": 122,
   "name": "Administration",  
  },
  {
   "id": 133,
   "name": "IT/Computer"
  }
]
  1. Job Position (relation with specialization collection, one specialization job have many job position)
[
  {
   "id": 1,
   "name": "Manager",
   "id_specialization": 122
  },
  {
   "id": 2,
   "name": "Front End Developer",
   "id_specialization": 133
  }
]
  1. Job (relation with job position)
[
  {
   "id": 1,
   "id_job_position": "1",
   "location": "New York" 
  },
  {
   "id": 2,
   "id_job_position": "2",
   "location": "Dallas"
  }
]

I want to make a filter by "specialization", if i choose "122" id of specialization, then i want to show job data which is job position is in that specialization.

[
  {
   "id": 1,
   "id_job_position": "1",
   "location": "New York" 
  }
]

Thanks before.

Upvotes: 0

Views: 230

Answers (1)

Demo - https://mongoplayground.net/p/1Bn1OUOODrT

Use $lookup

Performs a left outer join to an unsharded collection in the same database to filter in documents from the "joined" collection for processing. To each input document, the $lookup stage adds a new array field whose elements are the matching documents from the "joined" collection. The $lookup stage passes these reshaped documents to the next stage.

db.jobPosition.aggregate([
  {
    $match: {
      id_specialization: 122
    }
  },
  {
    "$lookup": {
      "from": "job",
      "localField": "id",
      "foreignField": "id_job_position",
      "as": "jobs"
    }
  },
  {
    $project: {
      jobs: 1
    }
  },
  {
    $unwind: "$jobs" //  break into individual documents can skip if only 1 document will come from lookup
  },
  {
    "$replaceRoot": {
      "newRoot": "$jobs"
    }
  },
  {
    $project: { _id: 0 }
  }
])

if only 1 document will come from the lookup

Demo - https://mongoplayground.net/p/CNevmFlEWWZ

db.jobPosition.aggregate([
  {
    $match: {
      id_specialization: 122
    }
  },
  {
    "$lookup": {
      "from": "job",
      "localField": "id",
      "foreignField": "id_job_position",
      "as": "jobs"
    }
  },
  {
    "$replaceRoot": {
      "newRoot": {
        "$first": "$jobs"
      }
    }
  },
  {
    "$project": {
      _id: 0
    }
  }
])

Upvotes: 1

Related Questions