mongodb - 我想从 mongo db 字段中提取一个子字符串并检查它是否可以被 4 整除
问题描述
我想从mongo db
字段中提取一个子字符串并检查它是否可以被 4 整除。
我有一些如下文件:
{
"form" : "form-1002",
"requestType" : "POST"
},
{
"form" : "form-1003",
"requestType" : "POST"
}
我想根据表单字段提取文档form-1002
,1002可以被2整除。然后根据查询结果更新请求类型。我怎样才能做到这一点?
解决方案
使用 MongoDB 4.0 及更高版本:
构造一个聚合管道,该管道使用$substrCP
来返回带有数字部分的表单字段的子字符串。
$toInt
获得子字符串后,使用or将其转换为数值$convert
。
$mod
将上一次运算的结果除以 2 时,使用运算符获得余数。
以下示例显示了具有不同字段的完整管道,显示了上述每个运算符的操作方式:
const pipeline = [
{ "$addFields": {
"formValue": {
"$toInt": {
"$substrCP": [
"$form",
5,
99999999
]
}
},
"remainder": {
"$mod": [
{
"$toInt": {
"$substrCP": [
"$form",
5,
99999999
]
}
},
2
]
},
"computedRequestType": {
"$cond": [
{
"$eq": [
{
"$mod": [
{
"$toInt": {
"$substrCP": [
"$form",
5,
99999999
]
}
},
2
]
},
0
]
},
"POST",
"GET"
]
}
} }
]
db.collection.aggregate(pipeline)
对于这两个文件,上述产量:
/* 1 */
{
"_id" : ObjectId("5b979ad11f21b55f5a1399c6"),
"form" : "form-1002",
"requestType" : "POST",
"formValue" : 1002,
"remainder" : 0,
"computedRequestType" : "POST"
}
/* 2 */
{
"_id" : ObjectId("5b979ad11f21b55f5a1399c7"),
"form" : "form-1003",
"requestType" : "POST",
"formValue" : 1003,
"remainder" : 1,
"computedRequestType" : "GET"
}
要更新集合,您可能需要添加另一个$out
在同一集合上使用运算符的管道,但管道将如下所示:
const pipeline = [
{ "$addFields": {
"requestType": {
"$cond": [
{ "$eq": [
{ "$mod": [
{ "$toInt": {
"$substrCP": [
"$form",
5,
99999999
]
} },
2
] },
0
] },
"POST",
"GET"
]
}
} },
{ "$out": "collection" }
]
db.collection.aggregate(pipeline)
推荐阅读
- c# - 如何在 azure function app v2 启动中调用一些代码逻辑
- python - 用于 Django 前端的 HTML 模板或 React?
- powershell - 在&运算符中传递参数值中的变量 - Powershell
- python - 是否有可能导入子模块的具体方式?
- razor - 在 razor 中的 html 中遇到 razor 的问题
- node.js - 无法安装节点 12.8
- rest - 有没有办法通过使用 REST api(或任何客户端解决方案)在 Sharepoint 上保存大量数据?
- elasticsearch - 在 Elastic Search 7.x 中删除连接关系
- mysql - LEFT JOIN 返回不相关的数据,它应该是 NULL
- python - 如何在 python 文件中使用命令自动安装软件包?