Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

83
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda