gpt4 book ai didi

mongodb - 在 mongoDb 中过滤查询嵌入式文档数组(3 级)

转载 作者:可可西里 更新时间:2023-11-01 10:45:03 24 4
gpt4 key购买 nike

我有一组图表。每个图都有几个 block 。每个 block 都有几个端口,它本身有多个对象作为字段。到目前为止我只能申请$filter$group在 block 上达到 1 级。我无法根据某些条件过滤到端口。

文档结构为:图表

[
{
"_id": "1",
"blocks": [
{
"port": [
{
"portType": {
"function": "input"
}
}
]
}
]
}
]

我想要实现的是获取所有具有 input 的端口的列表作为portType.function来自收藏

db.collection.aggregate([{$project:{"blocks.ports":{$filter:{input:"$blocks.ports",as:"ports",cond:{$in:["input","$$ports.portType.function"]}}}}}]);

预期输出:list<Ports>只有 portType.function作为输入。

实际输出:返回至少有一个端口作为“输入”的所有文档以及所有其他端口。

最佳答案

如果你想要一个 Port 对象的列表,你应该使用双 $unwind 阶段,然后 $match 用于 blocks.port .portType.function 最后使用 $project 阶段仅提取端口

db.collection.aggregate([
{
"$unwind": "$blocks"
},
{
"$unwind": "$blocks.port"
},
{
"$match": {
"blocks.port.portType.function": "input"
}
},
{
$project: {
_id: 0,
portType: "$blocks.port.portType",
}
}
])

如果您的 Port 对象包含您想要提取的其他字段,例如 Foo,您只需将这些字段添加到 $project阶段类似

$project: {
_id: 0,
portType: "$blocks.port.portType",
foo: "$blocks.port.foo"
...
}

关于mongodb - 在 mongoDb 中过滤查询嵌入式文档数组(3 级),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56785219/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com