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

773
Visualizações
In mongodb aggregation where to apply sort before lookup or after lookup?

I am writing an aggregation query where i want to perform a join in MongoDB between two collections and for that i am using $lookup, now my question is does $lookup change order of results by sort or not ?? because if it does that then i need to put my sort after $lookup and if not then i can use it before $lookup ??

My code is given below

brandmodel.aggregate(
     {$project: { '_id':0, 'brand_id': 1, 'brand_name':1, 'brand_icon':1, 'banner_image': 1, 'weight': 1} },
     {$lookup: {from: "student_coupons",localField: "brand_id",foreignField: "brand_id",as: "coupons"}},
     {$unwind : "$coupons"},
     {$sort: {weight: -1, "coupons.time_posted": -1}}, // SHOULD I WRITE THIS BEFORE LOOKUP OR AFTER LOOKUP
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

In MongoDB 3.6, the $lookup has a more expressive way where you can access the fields of the source document and do further pipeline operations within the $lookup stage. See documentation

As an example,

db.movies.aggregate([
{ $match : { _id : ObjectId("573a1390f29313caabcd414c")} },
{ $lookup : {from: "comments", 
 let: {'id' : '$_id' },
 pipeline: [
 { $match : { '$expr': { '$eq': [ '$movie_id', '$$id' ] } }},
 { $sort: {'date': -1} }
 ],
 as:  "comments"
  }
 }   
])

You have to declare any fields you want from the source collection in the let , do the matching as required (This is optional). Then you can use the pipeline stages that you need to apply in the collection being looked up.

over 4 years ago · Santiago Trujillo Relatório
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