按数组长度排序

nac*_*oab 4 mongodb

如何按数组字段的元素数对查询进行排序?

假设我有类似的记录

{
 title: '',
 author: '',
 votes: [id,id,id]
}
Run Code Online (Sandbox Code Playgroud)

我想按数组投票的长度排序

Nei*_*unn 15

$sizeMongoDB 2.6及更高版本的操作员的帮助下使用聚合框架:

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,
    }}
])
Run Code Online (Sandbox Code Playgroud)

很简单.

如果您没有可用的2.6版本,您仍然可以通过更多工作来完成此操作:

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,
    }}
])
Run Code Online (Sandbox Code Playgroud)

这就是它.