Home > Mobile >  How to sort for properties inside an other object in mongoose
How to sort for properties inside an other object in mongoose

Time:06-29

I have this document and I want to sort the other documents based on the views.

{
    "info": {
        "title": "Hello",
        "views": 500,
        "cover": "https:----",
        "duration": 203,
        "album": true,
        "lyrics": "---"
    },
    "_id": "62bb107c70a37ead49d685f8",
    "userName": [
        "Ben",
        "Mike"
    ],
    "audio": "---",
    "__v": 0
},

This is my sorting code at the moment:

const song = await Song.find({}).sort({ views: 1 }).limit(10)

This code is not working I am getting back unordered documents.

CodePudding user response:

Since the views field is inside info object, you have to use { "info.views": 1 }. This should give you the desired result.

const song = await Song.find({}).sort({ "info.views": 1 }).limit(10)
  • Related