Mongodb递归查询 [英] Mongodb recursive query
问题描述
我的taxon
集合中具有以下架构:
I have the following schema in my taxon
collection :
{
"_id": 1,
"na": [ "root_1",
"root_2",
"root_3" ],
"pa": 1
},{
"_id": 2,
"na": [ "name_1",
"name_2",
"name_3"],
"pa": 1
},{
"_id": 4,
"na": [ "otherName_1",
"otherName_2",
"otherName_3"],
"pa": 2
}
每个文档都通过父字段与另一个文档相关,该字段对应于其父文档的 _id
.
Each document is related to another by the parent field, which correspond to the _id
of it's parent.
我想执行递归搜索以得到以下结果:
I would like to perform a recursive search to get the following result:
{ "_id": 4,
"nameList": [ "otherName_1",
"name_1",
"root_1"]
}
从具有特定 _id
的文档中,获取每个父级的 na
数组的第一项,直到到达具有_id: 1
的文档
我目前通过执行X个查询(例如,按父文档一个,这里为3个)来获得此结果,但是我很确定可以使用单个查询来实现.我已经查看了新的 $ graphLookup 运算符,但无法设法解决它...
I currently get this result by performing X queries (one by parent document, here 3 for example), but I'm pretty sure that this can be achieved using a single query. I already looked at the new $graphLookup operator, but couldn't manage to get my way with it...
是否可以使用MongoDB 3.4.1在单个查询中实现?
Is it possible to achieve this in a single query using MongoDB 3.4.1?
修改
我每次都要运行50个文档,因此最佳的解决方案是将所有内容合并到一个查询中
I would run this for 50 documents each time, so the optimal solution would be to combine everything in a single query
例如,它看起来像
var listId = [ 4, 128, 553, 2728, ...];
var cursor = db.taxon.aggregate([
{$match:
{ _id: {$in: listId}}
}, ...
)];
并输出:
[{ "_id": 4,
"nameList": [ "otherName_1",
"name_1",
"root_1"]
}, { "_id": 128,
"nameList": [ "some_other_ame_1",
"some_name_1",
"root_1"]
}, { "_id": 553,
"nameList": [ "last_other_ame_1",
"last_name_1",
"root_1"]
} ... ]
在线试用: mongoplayground.net/p/Gfp-L03Ub0Y
推荐答案
您可以尝试以下聚合.
You can try below aggregation.
阶段$match - $graphLookup - $project
.
$reduce
从每个$graphLookup
nameList's
na
数组中选择第一个元素.
$reduce
to pick the first element from the each of $graphLookup
nameList's
na
array.
db.taxon.aggregate([{
$match: {
_id: {
$in: listId
}
}
}, {
$graphLookup: {
from: "taxon",
startWith: "$_id",
connectFromField: "pa",
connectToField: "_id",
as: "nameList"
}
}, {
$project: {
nameList: {
$reduce: {
input: "$nameList",
initialValue: [],
in: {
"$concatArrays": ["$$value", {
$slice: ["$$this.na", 1]
}]
}
}
}
}
}])
这篇关于Mongodb递归查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!