如何对集合中的数组进行排序 [英] How sort an array in a collection

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

问题描述

我一直在寻找对集合中特定内部数组进行排序的方法,我在symfony2中使用了doctrine-mongodb-bundle. 我的收藏:

I've been looking for sorting a specific inner array in a collection, I use doctrine-mongodb-bundle in symfony2. My collection :

"page":
{
    "_id": "56rgt46rt54h68rt4h6"
    "categories":
    [{
        "_id": "2g56rt1h65rt165165erg4"
        "products":[
            {"name":"A", "pos": 2},
            {"name":"B", "pos": 7},
            {"name":"C", "pos": 1},
            {"name":"D", "pos": 5}
        ]
    }]
}

我希望我有

"page":
{
    "_id": "56rgt46rt54h68rt4h6"
    "categories":
    [{
        "_id": "2g56rt1h65rt165165erg4"
        "products":[
            {"name":"C", "pos": 1},
            {"name":"A", "pos": 2},
            {"name":"D", "pos": 5},
            {"name":"B", "pos": 7}
        ]
    }]
}

还有我的实体:

/**
 * @MongoDB\EmbeddedDocument
 */
class Category
{
    /**
     * @MongoDB\Id(strategy="auto")
     */
    protected $id;

    /**
     * @MongoDB\String
     */
    protected $name;

    /** @MongoDB\EmbedMany(targetDocument="\Document\Product") */
    private $products = array();
}

/**
 * @MongoDB\EmbeddedDocument
 */
class Product
{
    /**
     * @MongoDB\Int
     */
    protected $pos;

    /**
     * @MongoDB\String
     */
    protected $name;
}

我是DoctrineMongoDBBundle的新手,累积内部数组(EmbedMany)可能不是一个好主意,最好有几个集合.因此,请保存参考.

I'm new with DoctrineMongoDBBundle, maybe is not a good idea to cumulate inner array (EmbedMany), and it would be better to have several collections. And so save reference.

推荐答案

假定products数组中的项目是唯一的,那么在MongoDB 2.4上,没有任何简单的服务器端支持即可按排序顺序维护此数组. .给定嵌套数组,最好的选择是对应用程序逻辑中的数组进行适当的排序(即在插入/更新或在检索/显示时).

Assuming the items in your products array are unique, there isn't any easy server-side support for maintaining this array in sorted order as at MongoDB 2.4. Your best option given the nested arrays will be to sort the arrays in your application logic as appropriate (i.e. on insert/update, or on retrieval/display).

如果需要对嵌套数组条目进行大量操作,则应考虑展平数据模型以使其更易于使用. MongoDB的设计目标应该是拥有适合您的应用程序用例的数据模型,并且在插入/更新/查询的便利性之间达到可接受的性能平衡.如果这样做没有任何意义,则绝对不必在单个集合/查询中为所有模型建模,并且应该准备对数据进行非规范化(重复).对于诸如产品< =>之类的多对多关系,通常会嵌入和取消规范化更新频率较低的实体(例如,在产品中嵌入类别).

If you need to do a lot of manipulation of nested array entries, you should consider flattening your data model to make it easier to work with. Your design goal with MongoDB should be to have a data model that is appropriate for your application use cases with acceptable performance balance between ease of inserting/updating/querying. You definitely do not have to model everything in a single collection/query if it doesn't make sense to do so, and you should be prepared to denormalize (duplicate) data. For many-to-many relationship such as products <=> categories it is typical to embed and denormalize whichever entity is less frequently updated (for example, embedding categories in products).

如果要按排序顺序保留数组,并且这些项不是唯一的,则MongoDB 2.4确实可以选择

If you want to persist arrays in sorted order and the items are not unique, MongoDB 2.4 does have the option to $push to a sorted array but this must be used in conjuction with a slice (array limit). If you $push identical entries to a sorted array you will end up with duplicates (so this likely isn't what you are after).

示例更新,假设示例中的page是集合名称:

Sample update, assuming page in your example was the collection name:

db.page.update(
    // Query
    { "_id": "56rgt46rt54h68rt4h6" },

    // Update sorted array
    // NB: referring by array index position 0, as there isn't a named reference
    { $push : {
        "categories.0.products" : { 

            // List of new elements to push
            $each : [
                { "name" : "E", "pos": 3 }
            ],

            // Sort by pos (ascending)
            $sort : { "pos" : 1 },

            // Maximum number of array elements (required for $sort)
            $slice : -100
        }
    }}
)

这篇关于如何对集合中的数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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