[英]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
操作:
- 創建一個臨時集合。
- 將索引從現有集合復制到臨時集合。
- 將文檔插入到臨時集合中。
- 使用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, $ substr和allowDiskUse 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.