mongodb - Mongodb:如何从逗号分隔的字符串中查找和删除字符串
问题描述
我有一个名为 groups 的字段,其中包含逗号分隔的字符串(即) groups:1,2,6,8 像这样。现在我想从该字段中删除 6 并更新,我的输出应该类似于 groups:1,2,8。由于我是 mongodb 的新手,我尝试并找不到在字段中查找和更新逗号分隔字符串的过程。
db.collection.find({ "groups": { "$regex": "6" } })
找到 6 并删除它,需要在“组”字段中更新为 1,2,8
解决方案
您可以使用聚合来更新。此解决方法删除了不需要的“,”
db.collection.update({},
[
{
$project: {
key: {
$filter: {
input: { $split: [ "$key","," ] },
cond: { $ne: ["$$this", "3" ]}
}
}
}
},
{
$project: {
key: {
$reduce: {
input: "$key",
initialValue: "",
in: {
$concat: [
"$$value",
{
"$cond": [{"$eq": ["$$value", ""]}, "", ", " ]
},
"$$this"
]
}
}
}
}
}
])
工作Mongo游乐场
推荐阅读
- java - 是否可以将 java 编译结果存储在 RAM 中而不是硬盘中?
- c - struct device中的fwnode在linux内核中做了什么?
- c# - Wrapper WebAPI vs IIS Url Rewrite
- java - 如何编写 removeDelivery 方法来删除 ArrayList 的元素
- javascript - 为什么我的代码不在日历上显示数据
- cplex - 使用 makeBranch 后如何检索变量分支
- android-studio - 未生成 Dagger2 ApplicationComponent(包括 git 项目)
- python - 无休止的程序执行
- javascript - 为什么如果点击了 onclick,sweetalert 无法显示
- javascript - 产生方波