Darkeezy
Darkeezy

Reputation: 23

Sort mongodb by two string values at the same time

For example I have schema like this below:

{
    "ID": "257185",
    "Name": "xxxx",
    "isAvailable": "NO",
    "isSuper": "NO"
}

I would like to sort it in mongo for values isAvailable and isSuper (string values) so the first record which I gonna recieve is YES / YES after that YES / NO or NO / YES.

How can I reach effect like this? Can I have any directions for that? I want to hide NO / NO records

Upvotes: 0

Views: 36

Answers (1)

J.F.
J.F.

Reputation: 15187

You can use a simple find method using mongoose like this:

model.find({"$or": [
    {
      "isAvailable": "YES"
    },
    {
      "isSuper": "YES"
    }
  ]}).sort({isAvailable: -1,isSuper: -1})

Or if you are using an aggregation pipeline you can add these stages:

db.collection.aggregate([
  {
    "$match": {
      "$or": [
        {
          "isAvailable": "YES"
        },
        {
          "isSuper": "YES"
        }
      ]
    }
  },
  {
    "$sort": {
      "isAvailable": -1,
      "isSuper": -1
    }
  }
])

Example here

Upvotes: 1

Related Questions