mongodb - 在文档中存储表达式/条件
问题描述
我是 mongodb 的新手,无法弄清楚以下是否可行。
我可以在文档的字段中存储条件(例如 gt、lt 等),然后在查询中使用它吗?
因此,鉴于以下文件:
{
title : "testTitle1",
score : 55,
condition : "gt"
}
{
title : "testTitle2",
score : 30,
condition : "lt"
}
并且给定 inputScore = 75,只返回 testTitle1 文档,因为 75 大于 ("gt") 55。第二个文档不会返回,因为它不小于 ("lt") 30。
有任何想法吗?
谢谢
解决方案
该查询使用聚合框架。我使用$switch
for 检查 是否condition
具有gt
orlt
值,并在与 比较后返回 a true
or 。这个比较结果给出了过滤条件以包含或拒绝输入文档。false
inputScore
score
matches
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 } }
] )
推荐阅读
- c - 如何使用 Libxml2 解析 XML 中的数据?LINUX + C 代码
- python - 如何使用 Poetry 将 Python 包部署到 Gitlab 包注册表?
- python-3.x - 没有空格的Python粘贴图像Alpha通道
- vue.js - 带有内置过滤器的下拉菜单不会在 Vuejs 中设置 v-model 值
- html - 为什么手机底部有多余的空间?
- kubernetes - 如何通过 Google Cloud Classic VPN 从外部网络连接到 Kubernetes 工作负载集群 IP?
- javascript - 通过保留 URL 加载 Firebase SDK 会出现“权限被拒绝”错误
- angular - Angular 8 和 Okta 注销不起作用,因为用户在应用程序内被重定向
- heroku - 检测 rails 配置失败将 HEROKU_DEBUG_RAILS_RUNNER=1 设置为调试
- python - Python:如何找到最频繁的元素组合?