arrays - MongoDB 聚合 - 嵌入式数组的投影中的 $filter
问题描述
我有一个复杂的 JSON 对象结构,其中包含 (N) 个嵌入式数组。单个条目是具有两个字段的对象: @name
和content
。我需要在投影阶段过滤它们(不使用$unwind
)以获得一个特定对象,其中@name
字段等于特定值:
productCategory: {$filter: {
input: '$characteristics.attributeGroup.attribute',
as: 'attribute',
cond: {
...?
}}
输入返回上述$characteristics.attributeGroup.attribute
结构。我试图在其中使用类似的东西,$cond: { $eq: ['$$attribute.@name', 'averageRating'] }
但它不起作用。
你能帮我在这里找到解决方案吗?
提前致谢!
解决方案
你可以试试,
$reduce
迭代数组循环attributeGroup
,并使用返回合并对象$mergeObjects
- 检查条件如果属性的类型是
object
然后再次检查第二个条件如果@name匹配则返回值否则移动到其他条件 $reduce
迭代数组循环attribute
,检查条件如果名称匹配则返回值
let name = "Artikelhinweise";
db.collection.aggregate([
{ $match: { "attributeGroup.attribute.@name": name } }, // name pass here
{
$project: {
attributeGroup: {
$reduce: {
input: "$attributeGroup",
initialValue: {},
in: {
$mergeObjects: [
"$$value",
{
$cond: [
{ $eq: [{ $type: "$$this.attribute" }, "object"] },
{
$cond: [
{ $eq: ["$$this.attribute.@name", name] }, // name pass here
{
"@name": "$$this.attribute.@name",
"content": "$$this.attribute.content"
},
"$$value"
]
},
{
$reduce: {
input: "$$this.attribute",
initialValue: {},
in: {
$cond: [
{ $eq: ["$$this.@name", name] }, // name pass here
{
"@name": "$$this.@name",
"content": "$$this.content"
},
"$$value"
]
}
}
}
]
}
]
}
}
}
}
}
])
推荐阅读
- java - PG JDBC 驱动程序中的错误 - MONEY DB 类型(双精度类型的错误值)
- python-2.7 - Solr 查询不适用于字段类型“文本”
- java - Java 9 JPMS 可以与 SPI 一起使用以在运行时动态加载插件吗?
- scala - 如何从 EMR 连接到 GCS
- python - sqlalchemy:hybrid_property 的布尔表达式
- python - 如何处理没有值的 XML 属性?
- azure - 使用 Azure 设备预配服务的 REST API 注册设备?
- r - R折叠并自动填充行中的空白
- mongodb - 引起:com.mongodb.MongoWriteException:E11000 重复键错误集合:Blog.Posts 索引:id 重复键:{:null }
- javascript - 悬停引导导航栏间隙问题