[英]how to query in mongodb with loop in same collection, until i find null or empty value?
I have stacked in a nested object.我已经堆叠在一个嵌套的 object 中。 here is my collection.
这是我的收藏。
{
"key": 1,
"subKey": ""
},
{
"key": 2,
"subKey": 1
},
{
"key": 3,
"subKey": 2
},
{
"key": 4,
"subKey": 3
}
I want to query Key:4
, which gives me result我想查询
Key:4
,这给了我结果
{
"key": 4,
"subKey": 3
}
after getting result i want to query "subKey": 3
as a key:"$subKey"
and i want to run a loop, until i find a empty subKey in our case It is Key:1
.得到结果后,我想查询
"subKey": 3
作为key:"$subKey"
并且我想运行一个循环,直到在我们的例子中找到一个空的 subKey 它是Key:1
。 and whenever i found an empty subKey
i want it document as a parent.每当我发现一个
subKey
时,我都希望它作为父项记录。
In the end, I want the result最后,我想要结果
{
"key": 4,
"parent":{"key":1,"subKey":"",....}
}
or similar.或类似的。
Is it possible by using MongoDB built-in function?是否可以使用 MongoDB 内置 function? if not available how do I achieve this goal?
如果不可用,我该如何实现这个目标?
also, I want an alternative solution for it if there is.另外,如果有的话,我想要一个替代解决方案。
You can achieve using $graphLookup
您可以使用
$graphLookup
来实现
db.collection.aggregate([
{
$graphLookup: {
from: "collection",
startWith: "$key",
connectFromField: "subKey",
connectToField: "key",
as: "keys"
}
}
])
If you want a match filter add it,如果你想要一个匹配过滤器添加它,
db.collection.aggregate([
{
$match: {
key: 4
}
},
{
$graphLookup: {
from: "collection",
startWith: "$key",
connectFromField: "subKey",
connectToField: "key",
as: "keys"
}
}
])
Important consideration:重要的考虑:
The $graphLookup stage must stay within the 100 MiB memory limit.
$graphLookup 阶段必须保持在 100 MiB memory 限制内。 If allowDiskUse: true is specified for the aggregate() operation, the $graphLookup stage ignores the option
如果为 aggregate() 操作指定了 allowDiskUse: true ,则 $graphLookup 阶段将忽略该选项
To transform the data, you cannot have duplicate keys in parent
object.要转换数据,
parent
object 中不能有重复的键。 So parent
should be an array所以
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
}
}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.