Home > Net >  How populate items to Model in order
How populate items to Model in order

Time:12-03

I have a question.

How do I sort the items which I add to the Model via .populate by some variable in the data?

The data I get:

"items": [
                {
                    "_id": "xxxx",
                    "name": "Item 1",
                    "price": 4000,
                    "order": 2,
                    "user": {
                        "_id": "xxxx",
                    }
                },
                {
                    "_id": "xxxx",
                    "name": "Item 2",
                    "price": 4000,
                    "order": 1,
                    "user": {
                        "_id": "xxxx",
                    }
                }
            ],

Here I want them to be sorted by the order variable. So Item 1 will be second and Item 2 will be first.

The order variable is not required, so if item does not have order, it should be sorted on last position.

CodePudding user response:

db.collection.aggregate({
"$sort": {order: 1}
})

you can use -1 for descending order. for live test check below link

mongodb sort result

  • Related