mongodb - Mongo按数组长度排序

假设我有这样的 mongo 文档:

问题 1

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

问题 2

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

有没有办法按答案的大小对集合进行排序?

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

最佳答案

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

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

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

更新现在聚合框架已经发布...

> 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
}

https://stackoverflow.com/questions/9040161/

相关文章:

mongodb - Cassandra、Membase、Hadoop、MongoDB、RDBMS等如

javascript - .save() 和使用 update() 之间的 Mongoose 区别

java - java中使用mongodb的createIndex()和ensureIndex()的

mongodb - 如何在mongodb中删除N个文档

mongodb - 如何列出 mongo shell 中的所有用户?

mongodb - "db.createUser is not a function"和 "pass

ruby-on-rails - 批量查找 mongoDB 记录(使用 mongoid ruby​​

mongodb - Mongoose中的级联样式删除

regex - Node.js 和 Mongoose 正则表达式查询多个字段

node.js - MongoDB Node findone如何处理没有结果?