sql >> Base de Datos >  >> NoSQL >> MongoDB

Ordenar por longitud de matriz

Use el marco de agregación con la ayuda de $size operador de MongoDB 2.6 y superior:

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,
    }}
])

Bastante simple.

Si no tiene una versión 2.6 disponible, aún puede hacerlo con un poco más de trabajo:

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,
    }}
])

Eso es más o menos.