3

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,

    },


]
1

1 Answer 1

2
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

Sign up to request clarification or add additional context in comments.

1 Comment

sort should be "$sort": { "offer": -1, "id": -1, }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.