我已经堆叠在一个嵌套对象中。这是我的收藏。
{
"key": 1,
"subKey": ""
},
{
"key": 2,
"subKey": 1
},
{
"key": 3,
"subKey": 2
},
{
"key": 4,
"subKey": 3
}
我想查询Key:4
,它给出了结果
{
"key": 4,
"subKey": 3
}
获得结果后,我想查询 "subKey": 3
作为 key:"$subKey"
并且我想运行一个循环,直到找到一个空的在我们的例子中,子 key 是Key:1
。每当我发现一个空的 subKey
时,我都希望它作为父项文档。
最后我想要结果
{
"key": 4,
"parent":{"key":1,"subKey":"",....}
}
或类似的。
使用MongoDB内置函数可以吗?如果不可用,我该如何实现这个目标?
另外,如果有的话,我想要一个替代解决方案。
最佳答案
您可以使用$graphLookup
来实现
db.collection.aggregate([
{
$graphLookup: {
from: "collection",
startWith: "$key",
connectFromField: "subKey",
connectToField: "key",
as: "keys"
}
}
])
如果您想要匹配过滤器,请添加它,
db.collection.aggregate([
{
$match: {
key: 4
}
},
{
$graphLookup: {
from: "collection",
startWith: "$key",
connectFromField: "subKey",
connectToField: "key",
as: "keys"
}
}
])
重要考虑因素:
The $graphLookup stage must stay within the 100 MiB memory limit. If allowDiskUse: true is specified for the aggregate() operation, the $graphLookup stage ignores the option
要转换数据,parent
对象中不能有重复的键。所以 parent
应该是一个数组
db.collection.aggregate([
{
$match: {
key: 4
}
},
{
$graphLookup: {
from: "collection",
startWith: "$key",
connectFromField: "subKey",
connectToField: "key",
as: "keys"
}
},
{
"$addFields": {
"parent": {
"$map": {
"input": "$keys",
"as": "res",
"in": {
"key": "$$res.key",
"subKey": "$$res.subKey"
}
}
},
"key": "$key",
}
},
{
$project: {
keys: 0
}
}
])
关于javascript - 如何在同一集合中循环查询 mongodb,直到找到 null 或空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62899888/