MongoDB聚合查询如何排除数组中的多个指定对象
MongoDB过滤排除数组中多个指定对象的实现方案
前置准备
先定义待排除的charges列表:
const excludedList = [ { "type": "asr", "dId": 123 }, { "type": "asr", "dId": 124 } // 追加其他需要排除的组合即可 ]
实现代码(适配MongoDB 3.6及以上版本,推荐)
直接在$filter的判断条件中校验当前条目不在排除列表中即可:
[ { "$project": { "_id": 0, "pId": 1, "charges": { "$filter": { "input": "$charges", "as": "charge", "cond": { "$not": { "$in": [ { "type": "$$charge.type", "dId": "$$charge.dId" }, excludedList ] } } } } } } ]
低版本兼容方案(MongoDB 3.6以下)
如果版本不支持对象直接匹配,可动态生成$nor判断条件,将所有排除项的匹配规则放到$nor数组中即可:
[ { "$project": { "_id": 0, "pId": 1, "charges": { "$filter": { "input": "$charges", "as": "charge", "cond": { "$nor": [ { "$and": [{ "$eq": ["$$charge.type", "asr"] }, { "$eq": ["$$charge.dId", 123] }] }, { "$and": [{ "$eq": ["$$charge.type", "asr"] }, { "$eq": ["$$charge.dId", 124] }] } // 有更多排除项按相同格式追加即可 ] } } } } } ]
结果说明
基于你提供的示例文档执行后,返回结果如下:
{ "pId": 12345, "charges": [ { "type": "asp", "dId": 125, "value": 130 }, { "type": "asn", "dId": 126, "value": 130 }, { "type": "aso", "dId": 127, "value": 150 } ] }
内容的提问来源于stack exchange,提问作者phani
相关产品推荐
相关产品推荐

