gpt4 book ai didi

mongodb - 是否有用于基于字段过滤所有嵌套/子文档的 Mongo 函数?

转载 作者:行者123 更新时间:2023-12-04 00:53:58 24 4
gpt4 key购买 nike

我在 MongoDB 中有一些文档,其中包含其他嵌套文档,它们都带有“事件”字段。例如:

{
"id": "PRODUCT1",
"name": "Product 1",
"active": true,
"categories": [
{
"id": "CAT-1",
"active": true,
"subcategories": [
{
"id": "SUBCAT-1",
"active": false
},
{
"id": "SUBCAT-2",
"active": true
}
]
},
{
"id": "CAT-2",
"active": false,
"subcategories": [
{
"id": "SUBCAT-3",
"active": true
}
]
}
]
}

有没有办法找到所有文档但只保留“事件”嵌套文档。

这是我想要的结果:

{
"id": "PRODUCT1",
"name": "Product 1",
"active": true,
"categories": [
{
"id": "CAT-1",
"active": true,
"subcategories": [
{
"id": "SUBCAT-2",
"active": true
}
]
}
]
}

事先知道我不知道文档架构。这就是为什么我需要一种条件通配符投影...(即*.active=true)。这是可能的还是必须在服务器端完成?

最佳答案

使用 $redact .

db.collection.aggregate(
[
{ $redact: {
$cond: {
if: { $eq:["$active", true] },
then: "$$DESCEND",
else: "$$PRUNE"
}
}
}
]
);

https://mongoplayground.net/p/7UMphkH5OWn

关于mongodb - 是否有用于基于字段过滤所有嵌套/子文档的 Mongo 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64137997/

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