Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

781
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda