Mongodb 基于类型和祖先字段从mongo db获取记录
在mongodb中,记录是这样存储的Mongodb 基于类型和祖先字段从mongo db获取记录,mongodb,Mongodb,在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,ty
{_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,.....}
我想按这样的顺序取记录
第一个祖先为零的记录
然后是父记录是我们搜索的第一条记录且其类型为“问题”的所有记录
然后是父项为我们搜索的第一条记录且类型为“section”的所有记录
预期产量为
{_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,.....}
请尝试此MongoDB shell命令:
db.collection.find().sort({ancestry:1, type: 1})
在排序字典不可用的不同语言中,排序参数可能使用2元组列表。类似于以下内容(Python):
@vinipsmaker的答案是好的。但是,如果
\u id
是随机数,或者存在不属于树结构的文档,则它无法正常工作。在这种情况下,以下代码将正常工作:
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是树结构中的文档数
如果树结构很大,或者您将多次进行排序,您可以通过在查询中使用进行优化,并在客户端对结果进行排序
此外,在
祖先
字段上创建索引将使两种情况下的代码都更快。您可能需要在此处使用多个查询以获得所需的效果
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;
}