如何通过聚合查询展示集合中符合条件的多级数组数据?
MongoDB聚合查询:筛选指定条件的Items数据
原始集合数据
[ { "Items": [ { "Key": "Key1", "Values": [ { "Value": "Value 1", "EndDT": "2024-01-31T15:43:53.000Z" }, { "Value": "Value 2", "EndDT": null } ] }, { "Key": "Key2", "Values": [ { "Value": "Value 3", "EndDT": "2024-01-31T15:43:53.000Z" }, { "Value": "Value 4", "EndDT": null } ] } ] }, { "Items": [ { "Key": "Key1", "Values": [ { "Value": "Value 5", "EndDT": null } ] }, { "Key": "Key4", "Values": [ { "Value": "Value 3", "EndDT": "2024-01-31T15:43:53.000Z" }, { "Value": "Value 4", "EndDT": null } ] } ] } ]
当前使用的聚合阶段
{ $match: { 'Items': { $elemMatch: { 'Key': 'Key1', 'Values': { $elemMatch: { 'EndDT': null } } } } } }
期望结果
[ { "Items": [ { "Key": "Key1", "Values": [ { "Value": "Value 2", "EndDT": null } ] } ] }, { "Items": [ { "Key": "Key1", "Values": [ { "Value": "Value 5", "EndDT": null } ] } ] } ]
解决方案
当前$match阶段仅筛选出包含符合条件元素的文档,但不会过滤文档内不符合要求的数组项。要得到期望结果,需在$match后添加数组过滤阶段:
完整聚合管道
[ { $match: { 'Items': { $elemMatch: { 'Key': 'Key1', 'Values': { $elemMatch: { 'EndDT': null } } } } } }, { $project: { Items: { $filter: { input: '$Items', cond: { $and: [ { $eq: ['$$this.Key', 'Key1'] }, { $gt: [{ $size: { $filter: { input: '$$this.Values', cond: { $eq: ['$$this.EndDT', null] } } } }, 0] } ] } } } } }, { $addFields: { Items: { $map: { input: '$Items', as: 'item', in: { Key: '$$item.Key', Values: { $filter: { input: '$$item.Values', cond: { $eq: ['$$this.EndDT', null] } } } } } } } } ]
阶段说明
- $match:先筛选出包含
Key为Key1且对应Values数组存在EndDT为null元素的文档,减少后续处理的数据量。 - $project:过滤
Items数组,仅保留Key为Key1且其Values数组包含目标元素的项。 - $addFields:对保留的
Items项,进一步过滤其Values数组,仅保留EndDT为null的元素,得到最终结构。
内容的提问来源于stack exchange,提问作者Awewewe Prog
相关产品推荐
相关产品推荐

