MongoDB聚合框架实现条件投影operator字段:匹配取对应值否则设为Not Found
使用MongoDB聚合框架实现operator字段投影需求
需求:在ref_docs集合中通过聚合框架添加名为operator的新字段,规则如下:
- 若文档的
answer_text包含ref_operators集合中某条文档的id值,operator字段取对应文档的value - 无匹配结果时,
operator设为'Not Found'
示例数据
ref_operators集合文档
[ { id: 'Jorge', value: 'Jorge' }, { id: 'Juan', value: 'Juan' } ]
ref_docs集合文档
[ { date_created: '2022-02-02', answer_text: 'Hello Jorge' }, { date_created: '2022-02-02', answer_text: 'Hello Juan' }, { date_created: '2022-02-02', answer_text: 'Hello Carlos' }, { date_created: '2022-02-02', answer_text: 'Hello Roberto' } ]
聚合解决方案
以下聚合管道可实现需求:
db.ref_docs.aggregate([ // 关联ref_operators,匹配answer_text包含id的文档 { $lookup: { from: "ref_operators", let: { answerText: "$answer_text" }, pipeline: [ { $match: { $expr: { $regexMatch: { input: "$$answerText", regex: "$id", options: "i" // 可选参数,开启大小写不敏感匹配 } } } } ], as: "matchedOperators" } }, // 根据匹配结果生成operator字段 { $project: { date_created: 1, answer_text: 1, operator: { $cond: { if: { $gt: [{ $size: "$matchedOperators" }, 0] }, then: { $arrayElemAt: ["$matchedOperators.value", 0] }, else: "Not Found" } } } } ])
代码说明
$lookup阶段:
- 关联
ref_operators集合,通过$regexMatch判断answer_text是否包含目标id - 匹配结果存入
matchedOperators数组字段
- 关联
$project阶段:
- 保留原有的
date_created和answer_text字段 - 用
$cond判断匹配数组长度:- 数组长度大于0时,取第一个匹配项的
value作为operator值 - 无匹配时赋值为
'Not Found'
- 数组长度大于0时,取第一个匹配项的
- 保留原有的
预期输出
[ { date_created: '2022-02-02', answer_text: 'Hello Jorge', operator: 'Jorge' }, { date_created: '2022-02-02', answer_text: 'Hello Juan', operator: 'Juan' }, { date_created: '2022-02-02', answer_text: 'Hello Carlos', operator: 'Not Found' }, { date_created: '2022-02-02', answer_text: 'Hello Roberto', operator: 'Not Found' } ]
内容的提问来源于stack exchange,提问作者Matias Ordoñez
相关产品推荐
相关产品推荐

