首页 > 解决方案 > Mongodb:如何从逗号分隔的字符串中查找和删除字符串

问题描述

我有一个名为 groups 的字段,其中包含逗号分隔的字符串(即) groups:1,2,6,8 像这样。现在我想从该字段中删除 6 并更新,我的输出应该类似于 groups:1,2,8。由于我是 mongodb 的新手,我尝试并找不到在字段中查找和更新逗号分隔字符串的过程。

db.collection.find({ "groups": { "$regex": "6" } }) 

找到 6 并删除它,需要在“组”字段中更新为 1,2,8

标签: mongodbmongoose

解决方案


您可以使用聚合来更新。此解决方法删除了不需要的“,”

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游乐场


推荐阅读