有一个物品(mongoose)模式,看起来像这样(简化到问题所在的部分):
{
brand: {
name: String,
},
title: String,
description: [{ lang: String, text: String }],
shortDescription: [{ lang: String, text: String }],
variants: {
cnt: Number,
attrs: [
{
displayType: String,
displayContent: String,
displayName: [{ lang: String, text: String }],
name: String,
},
],
}
}
我正在尝试通过语言筛选项目,因此我构建了以下查询:
db.items.aggregate([
{ $match: { 'description.lang': 'ca', 'shortDescription.lang': 'ca' } },
{ $project: {
'brand.name': 1,
title: 1,
description: {
'$filter': {
input: '$description',
as: 'description',
cond: { $eq: ['$$description.lang', 'ca'] }
}
},
shortDescription: {
'$filter': {
input: '$shortDescription',
as: 'shortDescription',
cond: { $eq: ['$$shortDescription.lang', 'ca'] }
}
},
'variants.cnt': 1,
'variants.attrs': 1
} }
])
它按预期工作:通过语言过滤description
和shortDescription
。我现在想知道是否也可以过滤每个variants.attrs.$.displayName
。有什么方法可以做到吗?
我一直在尝试使用$unwind
variant.attrs
,但是当我尝试再次$group
时完全迷失了方向,我不确定这是否是最佳方法...
description: [{ lang:'en', text: 'This item is awful' }, { lang: 'es', text: 'Este producto es increíble' }, ...]
- Miquel