Home > Back-end >  MongoDB sort by multiple fields on boolean type
MongoDB sort by multiple fields on boolean type

Time:06-07

First of all i need "isFavourite": true then "isReadByPro": false and then updatedAt:-1.

I tried below way but not working.

{ $sort: { updatedAt: -1 } },
{ $sort: { isReadByPro: 1 } },
{ $sort: { isFavourite: -1 } },
[
            {
                "_id": "628c8378c92d4b969cf4b53b",
                "post": {
                    "title": "project 94608"
                },
                "isFavourite": true,
                "isReadByPro": true,
                "updatedAt": "2022-06-06T10:34:05.776Z"
            },
            {
                "_id": "628f507192034120c7fc261a",
                "post": {
                    "title": "your payment test 1"
                },
                "isFavourite": true,
                "isReadByPro": true,
                "updatedAt": "2022-05-27T10:39:16.493Z"
            },
            {
                "_id": "628f50a792034120c7fc2681",
                "post": {
                    "title": "your payment test 3"
                },
                "isFavourite": true,
                "isReadByPro": true,
                "updatedAt": "2022-05-27T08:42:48.403Z"
            },
            {
                "_id": "628c76840ffe2cd088654d50",
                "post": {
                    "title": "showcase 1"
                },
                "isFavourite": false,
                "isReadByPro": true,
                "updatedAt": "2022-05-24T06:10:38.364Z"
            },
            {
                "_id": "628c780a0ffe2cd088654e21",
                "post": {
                    "title": "project 1 test"
                },
                "isFavourite": false,
                "isReadByPro": true,
                "updatedAt": "2022-05-27T06:30:54.058Z"
            },
            {
                "_id": "628c79cb5b4b0ee6020482df",
                "post": {
                    "title": "project 2 test"
                },
                "isFavourite": false,
                "isReadByPro": true,
                "updatedAt": "2022-05-27T06:30:54.058Z"
            }
]

CodePudding user response:

In order to sort by multiple fields, they should be on the same sorting object. The order of them is according to priority. This data is sorted first by isFavourite, then, all the documents with the same isFavourite value will be sorted between them by isReadByPro and so on.

{ $sort: {isFavourite: -1, isReadByPro: 1, updatedAt: -1} }
  • Related