我已經使用 mongodb 成功地將 csv 檔案匯入到我的 mongodb 資料庫中compass,在匯入檔案時,我可以選擇/選擇欄位的資料型別,但是當我嘗試將與另一個集合相關的欄位更改為 時ObjectId,我得到這個錯誤:
Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer
所以我不得不將該欄位保留為字串,即使該欄位與同一資料庫中另一個集合中的另一個欄位有關系。見下圖:
點擊圖片查看大圖。

從影像中,olist_order_items_dataset有一個欄位product_id,分別與和集合seller_id有關系,但這些欄位是作為字串而不是作為. 所以問題是如何建立這些欄位之間的關系?olist_products_datasetolist_sellers_datasetObjectId
我試圖將欄位更改為ObjectIdmongodb中的欄位,compass但我必須為每個檔案都這樣做,并且我在集合中有 112、650 個檔案。
uj5u.com熱心網友回復:
在 MongoDBCompass中,您可以運行mongosh(GUI 左下角)。
之后use leadDevAssignment您可以執行以下操作:
db.olist_order_items_datasets.update({
"product_id": {"$type": "string"},
"seller_id": {"$type": "string"}
},
[
{
"$set": {
"product_id": {"$toObjectId": "$product_id"},
"seller_id": {"$toObjectId": "$seller_id"}
}
}
],
{"multi": true}
)
在mongoplayground.net上試試。
或者,如果你想從Compass聚合中做到這一點,你可以這樣做:
db.olist_order_items_datasets.aggregate([
{
"$match": {
"product_id": {"$type": "string"},
"seller_id": {"$type": "string"}
}
},
{
"$set": {
"product_id": {"$toObjectId": "$product_id"},
"seller_id": {"$toObjectId": "$seller_id"}
}
},
{"$merge": "olist_order_items_datasets"}
])
在mongoplayground.net上試試。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/517025.html
