首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >根据类型和祖先字段从mongo数据库获取记录

根据类型和祖先字段从mongo数据库获取记录
EN

Stack Overflow用户
提问于 2013-05-11 21:50:11
回答 2查看 106关注 0票数 0

在mongodb中,记录是这样存储的

代码语言:javascript
复制
{_id:100,type:"section",ancestry:nil,.....}
{_id:300,type:"section",ancestry:100,.....}
{_id:400,type:"problem",ancestry:100,.....}
{_id:500,type:"section",ancestry:100,.....}
{_id:600,type:"problem",ancestry:500,.....}
{_id:700,type:"section",ancestry:500,.....}
{_id:800,type:"problem",ancestry:100,.....}

预期输出为

代码语言:javascript
复制
{_id:100,type:"section",ancestry:nil,.....}
{_id:400,type:"problem",ancestry:100,.....}
{_id:800,type:"problem",ancestry:100,.....}
{_id:300,type:"section",ancestry:100,.....}
{_id:500,type:"section",ancestry:100,.....}
{_id:600,type:"problem",ancestry:500,.....}
{_id:700,type:"section",ancestry:500,.....}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-05-12 00:14:01

尝试使用此MongoDB外壳命令:

代码语言:javascript
复制
db.collection.find().sort({ancestry:1, type: 1})

在排序字典不可用的情况下,不同的语言可以使用排序参数的二元组列表。如下所示(Python):

代码语言:javascript
复制
collection.find({}).sort([('ancestry', pymongo.ASCENDING), ('type', pymongo.ASCENDING)])
票数 1
EN

Stack Overflow用户

发布于 2013-05-12 07:07:18

@vinipsmaker的答案很好。但是,如果_ids是随机数,或者存在不属于树结构的文档,它就不能正常工作。在这种情况下,以下代码可以正常工作:

代码语言:javascript
复制
function getSortedItems() {
    var sorted = [];
    var ids = [ null ];
    while (ids.length > 0) {
        var cursor = db.Items.find({ ancestry: ids.shift() }).sort({ type: 1 });
        while (cursor.hasNext()) {
            var item = cursor.next();
            ids.push(item._id);
            sorted.push(item);
        }
    }
    return sorted;
}

注意,这段代码并不快,因为db.Items.find()将被执行n次,其中n是树结构中的文档数。

如果树结构很大,或者您要多次进行排序,则可以通过在查询中使用$in operator对此进行优化,并在客户端对结果进行排序。

此外,在ancestry字段上创建索引将使代码在任何一种情况下都更快。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16497768

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档