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

165
Views
Cómo usar la declaración condicional para ordenar en Mongodb

déjame ilustrar con un ejemplo, supongamos que mi colección es así,

 products = [ { id: 1, name: "a", offer: true, expiryDate: "23-03-2022" }, { id: 2, name: "b", offer: false,//no offer }, { id: 3, name: "c", offer: true, expiryDate: "01-01-2021"//already expired }, { id: 4, name: "d", offer: true, expiryDate: "01-06-2022" }, ]

Quiero aquí, los artículos ofrecidos vienen primero en orden descendente, no deben caducar y luego el artículo restante debe venir en orden descendente, por lo que el resultado sería así

 [ { id: 4, name: "d", offer: true, expiryDate: "01-06-2022" }, { id: 1, name: "a", offer: true, expiryDate: "23-03-2022" }, { id: 3, name: "c", offer: true, expiryDate: "01-01-2021" }, { id: 2, name: "b", offer: false, }, ]
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

db.collection.aggregate([ { "$match": {} }, { "$set": { "offer": { "$cond": { "if": { "$lt": [ { "$toDate": "$expiryDate" }, "$$NOW" ] }, "then": false, "else": true } }, "expiryDate": { "$toDate": "$expiryDate" } } }, { "$sort": { "expiryDate": -1, "offer": -1 } } ])

parque infantil mongo

over 4 years ago · Santiago Trujillo Report
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!