1

I'm trying to sort this in MongoDB with mongojs on a find():

{
    "songs": {
        "bNppHOYIgRE": {
            "id": "bNppHOYIgRE",
            "title": "Kygo - ID (Ultra Music Festival Anthem)",
            "votes": 1,
            "added": 1428514707,
            "guids": [
                "MzM3NTUx"
            ]
        },
        "izJzdDPH9yw": {
            "id": "izJzdDPH9yw",
            "title": "Benjamin Francis Leftwich - Atlas Hands (Samuraii Edit)",
            "votes": 1,
            "added": 1428514740,
            "guids": [
                "MzM3NTUx"
            ]
        },
        "Yifz3X_i-F8": {
            "id": "Yifz3X_i-F8",
            "title": "M83 - Wait (Kygo Remix)",
            "votes": 0,
            "added": 1428494338,
            "guids": []
        },
        "nDopn_p2wk4": {
            "id": "nDopn_p2wk4",
            "title": "Syn Cole - Miami 82 (Kygo Remix)",
            "votes": 0,
            "added": 1428494993,
            "guids": []
        }
    }
}

and I want to sort the keys in the songs on votes ascending and added descending.

I have tried

db.collection(coll).find().sort({votes:1}, function(err, docs) {});

but that doesn't work.

Juan Carlos Farah
  • 3,829
  • 30
  • 42
  • 1
    There is no way to sort keys in a way you trying to do. You should change structure if you need to sort them. – evilive Apr 08 '15 at 18:21

1 Answers1

1

If this is an operation that you're going to be doing often, I would strongly consider changing your schema. If you make songs an array instead of a map, then you can perform this query using aggregation.

db.coll.aggregate([{ "$unwind": "$songs" }, { "$sort": { "songs.votes": 1, "songs.added": -1 }}]);

And if you put each of these songs in a separate songs collection, then you could perform the query with a simple find() and sort().

db.songs.find().sort({ "votes": 1, "added": -1 });

With your current schema, however, all of this logic would need to be in your application and it would get messy. A possible solution would be to get all of the documents and while iterating through the cursor, for each document, iterate through the keys, adding them to an array. Once you have all of the subdocuments in the array, sorting the array according to votes and added.

It is possible, but unnecessarily complex. And, of course, you wouldn't be able to take advantage of indexes, which would have an impact on your performance.

You already include the key inside the subdocument, so I would really recommend you reconsider your schema.

Juan Carlos Farah
  • 3,829
  • 30
  • 42