How to set preferences with sorting in mongodb aggregation

Viewed 28

I'm trying to aggregate query with the following data:

Here is my input data:

[{
    wishlist: true,
    productName: "product1",
    itemsInStock: 5
}, {
    wishlist: false,
    productName: "product2",
    itemsInStock: 25
}, {
    wishlist: false,
    productName: "product3",
    itemsInStock: 0
}, {
    wishlist: true,
    productName: "product4",
    itemsInStock: 17
}, {
    wishlist: false,
    productName: "product5",
    itemsInStock: 12
}, {
    wishlist: true,
    productName: "product6",
    itemsInStock: 0
}]

What I need my response is as follows:

-> wishlist & product name should be prioritized

-> itemsInStock should not be prioritized based on numbers but all itemsInStock: 0 should be at last preference

[{
    wishlist: true,
    productName: "product1",
    itemsInStock: 5
}, {
    wishlist: true,
    productName: "product4",
    itemsInStock: 17
}, {
    wishlist: false,
    productName: "product2",
    itemsInStock: 25
}, {
    wishlist: false,
    productName: "product5",
    itemsInStock: 12
}, {
    wishlist: true,
    productName: "product6",
    itemsInStock: 0
}, {
    wishlist: false,
    productName: "product3",
    itemsInStock: 0
}]

1 Answers

Simply do a $sort with your defined ordering.

db.collection.aggregate([
  {
    $sort: {
      wishlist: -1,
      productName: 1,
      itemsInStock: -1
    }
  }
])

Here is the Mongo playground for your reference.

Related