按数组长度排序 [英] Sort by array length

查看:61
本文介绍了按数组长度排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

假设我有类似的记录

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

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

I would like to do sort by the length of the array votes

推荐答案

$size 操作符来自 MongoDB 2.6 及更高版本:

Use the aggregation framework with help from the $size operator from MongoDB 2.6 and upwards:

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

很简单.

如果您没有可用的 2.6 版,您仍然可以多做一点工作:

If you do not have a version 2.6 available you can still do this with a little more work:

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

差不多就是这样.

这篇关于按数组长度排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆