score:0

Try this one:

db.collection.aggregate([
  {
    $addFields: {
      sortQuantity: { $cond: [ { $lte: ["$quantity", 0 ] }, 0, 1 ] }
    }
  },
  {
    $sort: {
      sortQuantity: 1,
      sort_order: -1
    }
  },
  { $unset: "sortQuantity" }
])

Mongo Playground

score:0

You can use

  • $facet to categorize incoming data into quantity>0 and quantity <=0
  • $sort to sort as you expected
  • $concatArray to concat both array into one array
  • $unwind to deconstruct the array
  • $replaceRoot to make the deconstructed variable as root

here is the ocde

db.collection.aggregate([
  {
    "$facet": {
      "lteZero": [
        {
          $match: {
            $expr: {
              $lte: [ "$quantity", 0 ]
            }
          }
        },
        { $sort: { sort_order: -1, quantity: 1 } }
      ],
      "gtZero": [
        {
          $match: {
            $expr: {
              $gt: [ "$quantity", 0 ]
            }
          }
        },
        { $sort: { sort_order: -1, quantity: 1 } }
      ]
    }
  },
  {
    "$project": {
      combined: {
        "$concatArrays": [ "$gtZero", "$lteZero" ]
      }
    }
  },
  { "$unwind": "$combined" },
  { "$replaceRoot": { "newRoot": "$combined" } }
])

working Mongo playground

score:0

It is simple and easy, you may use a cursor.sort() function to order the collection:

db.collection.find().sort( { quantity: -1 } )

These examples return all documents in the collection named collection sorted by the quantity field in descending order. Specify a value to $orderby of negative one (e.g. -1, as above) to sort in descending order or a positive value (e.g. 1) to sort in ascending order.

For more information please visit: https://docs.mongodb.com/manual/reference/method/cursor.sort/


More questions

More questions with similar tag