簡體   English   中英

如何將整個集合中的int字符轉換為字符串?

[英]How to convert a string with characters in the int for the entire collection?

我有一個類似的外觀集合:

_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。

在文檔中無處找不到我該怎么做,我真的必須使用Python來獲取每個值,刪除貨幣符號並使用update方法來做到這一點嗎? 我有將近8,000,000條記錄,它將很長。

如何使用收集方法做到這一點? 或使用Python最快的方法是什么?

如果要轉換整個集合,則可以使用“聚合”管道來完成。

你需要使用的貨幣轉換為字符串$substr$toInt($toDouble ,或$convert任何適合你的情況下)在$project階段和$out作為聚集的最后階段。 $out將聚集管道的結果寫入給定的集合名稱。

但是在使用$out要小心。 根據mongodb官方文檔:

創建新收藏

如果$out操作尚不存在,則它在當前數據庫中創建一個新集合。 在聚合完成之前,該集合不可見。 如果聚合失敗,則MongoDB不會創建集合。

替換現有集合

如果$out操作指定的集合已經存在,則在聚合完成后, $out階段用新的結果集合原子替換現有的集合。 具體來說, $out操作:

  1. 創建一個臨時集合。
  2. 將索引從現有集合復制到臨時集合。
  3. 將文檔插入到臨時集合中。
  4. 使用dropTarget:true調用db.collection.renameCollection以將臨時集合重命名為目標集合。

$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 aggregation或通過刪除$ out階段並檢查aggregation管道的結果來仔細檢查該值。

有關詳細信息,請閱讀mongodb官方文檔$ out$ toInt$ toDouble$ convert, $ substrallowDiskUse

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM