【问题标题】:How to convert a string with characters in the int for the entire collection?如何为整个集合转换带有 int 字符的字符串?
【发布时间】:2019-06-28 20:52:18
【问题描述】:

我收藏了一个类似的样子:

_id:5d0fe0dcfd8ea94eb4633222
Category:"Stripveiling (Nederlands)"
Category url:"https://www.catawiki.nl/a/11-stripveiling-nederlands"
Lot title:"Erwin Sels (Ersel) - Originele pagina"
Seller name:"Stripwereld"
Seller country:"Nederland"
Bids count:21
Winning bid:"€ 135"
Bid amount:"Closed"
Lot image:"https://assets.catawiki.nl/assets/2011/11/17/7/4/c/74c53540-f390-012e-..."

我需要将“中标”字段更改为 int。即移除货币符号并将整个集合从字符串转换为 int。

在文档中我找不到如何做到这一点,我真的必须用 Python 获取每个值,删除货币符号并使用方法更新来做到这一点吗?我有将近 8,000,000 条记录,会很长。

如何使用收集方法做到这一点?或者用 Python 最快的选择是什么?

【问题讨论】:

  • 都是“币号”形式的中标吗?
  • @AbdeslemSMAHI 是的
  • int(currency_string[1:].strip()) - 这是假设前两个字符中有一个字符串是货币符号和''空格字符。
  • @MFK34 我用python将字符串转换为int没有问题,特别是因为不需要strip(),你可以只用int()。我不知道如何在 mongodb 中进行所有更新

标签: python-3.x mongodb mongodb-compass


【解决方案1】:

如果要转换整个集合,可以使用聚合管道来完成。

您需要在$project 阶段和$out 作为聚合的最后阶段使用$substr$toInt($toDouble$convert 将货币转换为字符串。 $out 将聚合管道的结果写入给定的集合名称。

但在使用$out 时要小心。根据官方 mongodb 文档:

创建新收藏

$out 操作会在当前数据库中创建一个新集合(如果尚不存在)。这 在聚合完成之前,集合是不可见的。如果 聚合失败,MongoDB 不会创建集合。

替换现有集合

如果$out操作指定的集合已经存在,那么在完成 聚合,$out 阶段自动替换现有的 与新结果集合的集合。具体来说,$out 操作:

  1. 创建一个临时集合。
  2. 从现有的索引复制 集合到临时集合。
  3. 将文档插入到 临时收集。
  4. 调用 db.collection.renameCollection dropTarget: true 将临时集合重命名为目标 收藏。

$out 操作不会更改存在于 以前的收藏。如果聚合失败,$out 操作 不对现有集合进行任何更改。

试试这个:

db.collection_name.aggregate([
    {
        $project: {
            category : "$category",
            category_name : "$category_name",
            lot_title : "$lot_title",
            seller_name : "$seller_name",
            seller_country : "$seller_country",
            bid_count : "$bid_count",
            winning_bid : { $toInt : {$substr : ["$winning_bid",2,-1]}},
            bid_amount : "$bid_amount",
            lot_image : "$lot_image"
        }
    },{
        $out : "collection_name"
    }
])

您可能需要使用allowDiskUse : true 作为聚合管道的一个选项,因为您有很多文档,它可能会超过 16MB 的 mongodb 限制。

不要忘记将collection_name替换为实际的集合名称,并在集合中需要的$project阶段包含所有必填字段。请先使用不同的temporary_collection 仔细检查该值,或者仅删除$out 阶段并检查aggregation 管道的结果。

有关详细信息,请阅读官方 mongodb 文档$out$toInt$toDouble$convert,$substrallowDiskUse

【讨论】:

  • 你好。它对我不起作用,因为我的 mongodb 版本是 3.6.4。此功能出现在 4.0 版本中。
  • 我认为它在 MongoDB 2.6 版中可用,后来在 3.2 版中进行了更改(具有附加功能),因此它应该适合您。您也可以从官方 $out 文档中确认:docs.mongodb.com/manual/reference/operator/aggregation/out
  • 我的意思是 $toInt 和 $convert 是 4.0 版中的新功能。你可以检查一下。
  • 现在我正在备份我的数据库并在恢复到新版本之后,然后我尝试你的代码。
  • 哦,好吧,你说的是$toInt$convert。我明白了
猜你喜欢
  • 2017-12-20
  • 1970-01-01
  • 1970-01-01
  • 2017-06-06
  • 2023-02-15
  • 2020-09-03
  • 1970-01-01
  • 1970-01-01
  • 2020-11-30
相关资源
最近更新 更多