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

81
Views
Retrieving a relationship field in mongodb aggregation

I am using mongodb aggregation with a collection named files that has a relationship with another collection named file_upload.

files = {
 type: String,
 media:  { type: Schema.Types.ObjectId, ref: 'file_upload', required: true },
}

file_upoad = {
 name: String,
}

This is the query

const data = await strapi.query('files').model.aggregate([
      {
          $lookup: {
              from: "analytics",
              localField: "_id",
              foreignField: "file_id",
              as: "hits",
          }
      },
      { $unwind: '$hits' },
      { $group: { _id: "$_id", hitsCount: { $sum: 1 } } },
      { $sort: { hitsCount: -1 } },
      { $limit: 1 },
  ]) 

my goal is to retrieve the media as part of the result since it is a relationship field, at the moment I get this

[
{
    "_id": "61fd74367b6ee77b89bae34d",
    "hitsCount": 12
},
{
    "_id": "61fd74367b6ee77b89sddfee",
    "hitsCount": 8
}
]

expected result

[
 {
    "_id": "61fd74367b6ee77b89bae34d",
    "hitsCount": 12,
    "media": {
           name:"name1"
    }
 },
{
    "_id": "61fd74367b6ee77b89sddfee",
    "hitsCount": 8,
     "media": {
          name:"name2"
     }
}
]
about 4 years ago · Juan Pablo Isaza
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!