Mongodb sort command to sort database on multiple conditions

await Product
  .aggregate([{
    $match: {
      $expr: {
        keyword,
        category
      },
    },
  }, {
    $addFields: {
      isInStock: { // Helper field. This is 1 if there are items in stock.
        $cond: {
          if: "$countInStock",
          then: 1,
          else: 0
        }
      }
    }
  }, {
    $sort: {
      isInStock: -1,
      price: -1,
    },
  }, {
    $skip: page
  }, {
    $limit: pageSize
  }])
  .populate("categories.category", "id cat_name slug");
Topics: MongoDB

Related Code Examples