Mongo按数组长度排序 [英] Mongo order by length of array

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

问题描述

让我们说我有像这样的mongo文档:

Lets say I have mongo documents like this:

问题1

{
    answers:[
       {content: 'answer1'},
       {content: '2nd answer'}
    ]
}

问题2

{
    answers:[
       {content: 'answer1'},
       {content: '2nd answer'}
       {content: 'The third answer'}
    ]
}

有没有一种方法可以根据答案的大小对集合进行排序?

Is there a way to order the collection by size of answers?

经过一番研究,我看到了建议添加另一个字段的建议,该字段将包含一些答案并将其用作参考,但是可能有本机的方法吗?

After a little research I saw suggestions of adding another field, that would contain number of answers and use it as a reference but may be there is native way to do it?

推荐答案

我认为您也许可以使用$size,但这只是查找一定大小的数组,而不是排序.

I thought you might be able to use $size, but that's only to find arrays of a certain size, not ordering.

从mongo文档中: http://www.mongodb.org/display/DOCS/Advanced+ Queries#AdvancedQueries-%24size

From the mongo documentation: http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24size

您不能使用$ size查找一定范围的大小(例如:元素多于1个的数组).如果需要查询范围,请创建一个额外的尺寸字段,并在添加元素时增加该字段.索引不能用于查询的$ size部分,尽管如果包含其他查询表达式,则可以使用索引来搜索该查询表达式的该部分的匹配项.

You cannot use $size to find a range of sizes (for example: arrays with more than 1 element). If you need to query for a range, create an extra size field that you increment when you add elements. Indexes cannot be used for the $size portion of a query, although if other query expressions are included indexes may be used to search for matches on that portion of the query expression.

看起来您可以使用尚未推出的新聚合框架 edit:轻松完成此操作. http://www.mongodb.org/display/DOCS/Aggregation+Framework

Looks like you can probably fairly easily do this with the new aggregation framework, edit: which isn't out yet. http://www.mongodb.org/display/DOCS/Aggregation+Framework

更新,现在聚合框架已退出...

Update Now the Aggregation Framework is out...

> db.test.aggregate([
  {$unwind: "$answers"}, 
  {$group: {_id:"$_id", answers: {$push:"$answers"}, size: {$sum:1}}}, 
  {$sort:{size:1}}]);
{
"result" : [
    {
        "_id" : ObjectId("5053b4547d820880c3469365"),
        "answers" : [
            {
                "content" : "answer1"
            },
            {
                "content" : "2nd answer"
            }
        ],
        "size" : 2
    },
    {
        "_id" : ObjectId("5053b46d7d820880c3469366"),
        "answers" : [
            {
                "content" : "answer1"
            },
            {
                "content" : "2nd answer"
            },
            {
                "content" : "The third answer"
            }
        ],
        "size" : 3
    }
  ],
  "ok" : 1
}

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

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