在mongodb中,记录是这样存储的
{_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,.....}预期输出为
{_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,.....}发布于 2013-05-12 00:14:01
尝试使用此MongoDB外壳命令:
db.collection.find().sort({ancestry:1, type: 1})在排序字典不可用的情况下,不同的语言可以使用排序参数的二元组列表。如下所示(Python):
collection.find({}).sort([('ancestry', pymongo.ASCENDING), ('type', pymongo.ASCENDING)])发布于 2013-05-12 07:07:18
@vinipsmaker的答案很好。但是,如果_ids是随机数,或者存在不属于树结构的文档,它就不能正常工作。在这种情况下,以下代码可以正常工作:
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字段上创建索引将使代码在任何一种情况下都更快。
https://stackoverflow.com/questions/16497768
复制相似问题