Sort by array length

How can I sort a query by the number of elements in an array field?

Say I have entries like

{
 title: '',
 author: '',
 votes: [id,id,id]
}

I would like to sort by the length of the array of voices

+4
source share
2 answers

Use the aggregation structure using the operator from MongoDB 2.6 and higher: $size

db.collection.aggregate([
    // Project with an array length
    { "$project": {
        "title": 1,
        "author": 1,
        "votes": 1,
        "length": { "$size": "$votes" }
    }},

    // Sort on the "length"
    { "$sort": { "length": -1 } },

    // Project if you really want
    { "$project": {
        "title": 1,
        "author": 1,
        "votes": 1,
    }}
])

Simple enough.

If you do not have version 2.6, you can do this a little more:

db.collection.aggregate([
    // unwind the array
    { "$unwind": "$votes" },

    // Group back
    { "$group": {
        "_id": "$id",
        "title": { "$first": "$title" },
        "author": { "$first": "$author" },
        "votes": { "$push": "$votes" },
        "length": { "$sum": 1 }
    }},

    // Sort again
    { "$sort": { "length": -1 } },

    // Project if you want to
    { "$project": {
        "title": 1,
        "author": 1,
        "votes": 1,
    }}
])

This is pretty much the case.

+14
source

With regular queries, you can sort only matching documents by field values. Aggregation requests will allow you to calculate the size of the array and sort by these values. The disadvantage of using aggregation is that it can be slow.

, . (, voteCount), votes. . , . , .

+3

Source: https://habr.com/ru/post/1542645/


All Articles