2

Having data like below.

{
    "summary": "testing api1",
    "UpdatedDate": {
        "$date": "2018-12-30T00:00:00.000Z"
    },
    "status": "draft"
},
{
    "summary": "testing api2",
    "UpdatedDate": {
        "$date": "2018-12-30T00:00:00.000Z"
    },
    "status": "published"
},
{
    "summary": "testing api3",
    "UpdatedDate": {
        "$date": "2018-12-30T00:00:00.000Z"
    },
    "status": "delete"
}

I want to sort based "status" For ex: If I have given sort by status "published" then I need data like below

{
    "summary": "testing api2",
    "UpdatedDate": {
        "$date": "2018-12-31T00:00:00.000Z"
    },
    "status": "published"
},
{
    "summary": "testing api1",
    "UpdatedDate": {
        "$date": "2018-12-30T00:00:00.000Z"
    },
    "status": "draft"
},
{
    "summary": "testing api3",
    "UpdatedDate": {
        "$date": "2019-01-01T00:00:00.000Z"
    },
    "status": "delete"
}

It's possible in mongodb? or anything available similar like this?

1 Answers1

2

Ideally, you would assign a numerical value. But you can do it just as you have it with Aggregation framework.

Something like this with $addFields and $cond:

db.getCollection("yourcollection").aggregate([
  {
    $addFields: {
      sortNum: {
        $cond: [
          { $eq: ["$status", "published"] },
          0,
          { $cond: [{ $eq: ["$status", "draft"] }, 1, 2] }
        ]
      }
    }
  },

  {
    $sort: {
      sortNum: 1
    }
  }
]);

OR With $switch

db.collection.aggregate([{
    $addFields: {
      sortNum: {
        $switch: {
          branches: [
            {
              case: {
                $eq: ["$status", "published"]
              },
              then: 1
            },
            {
              case: {
                $eq: ["$status", "delete"]
              },
              then: 2
            },
            {
              case: {
                $eq: ["$status", "draft"]
              },
              then: 3
            }
          ],
          default: 0
        }
      }
    }
  },
  {
    $sort: {
      sortNum: 1
    }
  }]);
ambianBeing
  • 3,449
  • 2
  • 14
  • 25