I have MongoDB model called candidates
appliedJobs: [
{
job: { type: Schema.ObjectId, ref: "JobPost" },
date:Date
},
],
candidate may have multiple records in appliedJobs
array. There I refer to the jobPost
.
jobPost
has the companyName
, property.
companyName: String,
What I want is to get the company names with send job applications counts. For an example
|Company|Applications|
|--------|---------------|
|Facebook|10 applications|
|Google|5 applications|
I created this query
Candidate.aggregate([
{
$match: {
appliedJobs: { $exists: true },
},
},
{ $group: { _id: '$companyName', count: { $sum: 1 } } },
])
The problem here is I can’t access the companyName
like this. Because it’s on another collection. How do I solve this?
2
Answers
In order to get data from another collection you can use
$lookup
(nore efficient) orpopulate
(mongoose – considered more organized), so one option is:See how it works on the playground example
Simply
$unwind
theappliedJobs
array. Perform$lookup
to get thecompanyName
. Then,$group
to get count of applications by company.Here is the Mongo Playground for your reference.