批量删除收藏中的特殊字母

时间:2020-03-16 14:06:42

标签: mongodb mongodb-query

编辑:

让我们说我有一个Mongo数据库,其中包含一个集合,可以称之为产品。在这个集合中,我想从某个字段的所有条目中删除所有特殊字符,比如说所有点,比如说价格。 另外,我将如何替换所有对象的信息条目?

我将如何通过mongo shell做到这一点?

Example:

_id: 123324erwerew
name: 'moisture cream'
price: 30.00
info: 'Good Cream'

_id: 343324erwerew
name: 'moisture cream two'
price: 40.00
info: 'Good Cream also'

让我们说两个地方的信息都应该是:“有史以来最好的奶油”,并且两个价格上的点都应该消失

1 个答案:

答案 0 :(得分:0)

如果您的价格类似于30.1140.11,则以下管道更新命令将使价格"3011""4011"以及将信息设置为best cream ever

db.products.updateMany({}, [
    {
        $set: {
            price: {
                $reduce: {
                    input: { $split: [{ $toString: "$price" }, "."] },
                    initialValue: "",
                    in: { $concat: ["$$value", "$$this"] }
                }
            }
        }
    },
    {
        $set: {
            info: "best cream ever"
        }
    }
])

关于价格更新的说明:

  1. 价格值转换为字符串
  2. 结果字符串由定界符.分隔
  3. 然后使用$ reduce将
  4. 结果部分连接回一个字符串

在mongodb v4.4中,$replaceOne运算符对此进行了简化