首页 > 解决方案 > 在文档中存储表达式/条件

问题描述

我是 mongodb 的新手,无法弄清楚以下是否可行。

我可以在文档的字段中存储条件(例如 gt、lt 等),然后在查询中使用它吗?

因此,鉴于以下文件:

{
    title : "testTitle1",
    score : 55,
    condition : "gt"
}

{
    title : "testTitle2",
    score : 30,
    condition : "lt"
}

并且给定 inputScore = 75,只返回 testTitle1 文档,因为 75 大于 ("gt") 55。第二个文档不会返回,因为它不小于 ("lt") 30。

有任何想法吗?

谢谢

标签: mongodb

解决方案


该查询使用聚合框架。我使用$switchfor 检查 是否condition具有gtorlt值,并在与 比较后返回 a trueor 。这个比较结果给出了过滤条件以包含或拒绝输入文档。falseinputScorescorematches

var inputScore = 75;

db.gtlt.aggregate( [
  { $addFields: { 
             matches: {
                 $switch: {
                     branches: [
                       { 
                          case: { $eq : [ "$condition", "gt" ] },
                          then: { $cond: [ { $gt: [ inputScore, "$score" ] }, true, false ] }
                       },
                      {
                         case: { $eq : [ "$condition", "lt" ] },
                         then:  { $cond: [ { $lt: [ inputScore, "$score" ] }, true, false ] }
                      },
                   ],
                   default: false
               }
           }
  } },
  { $match: { matches: true } },
  { $project: { matches: 0 } }
] )

推荐阅读