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

303
Views
How to use conditional statement for sort in Mongodb

let me illustrate with an example, suppose my collection is like this,

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"
    },
]

I want here, the offered items comes first in descending order, it should not expire and then the remaining item should come in descending order so result would be like this

   [


    {
        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
    }
  }
])

mongoplayground

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!