如何在 Mongodb 中使用条件语句进行排序

How to use conditional statement for sort in Mongodb

让我举个例子, 假设我的collection是这样的,

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

我要这里,提供的物品降序排列在前, 它不应该过期,然后剩余的项目应该进来 降序所以结果是这样的

   [


    {
        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,

    },


]
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