mongodbからcsvにデータをエクスポートすると、pythonスクリプトでフィールド名が見つからないという問題があります。型フィールド名は最初のレコードに存在しますが、残りのレコードには表示されません。存在しない場合は、型フィールドにnull値を与えるPythonスクリプトを書く方法。jsonデータをmongodbからcsvにエクスポート
MongoDBのコレクションのサンプル:
"stages": [
{
"interview": false,
"hmNotification": false,
"hmStage": false,
"type": "new",
"isEditable": false,
"order": 0,
"name": {
"en": "New"
},
"stageId": "51d1a2f4c0d9887b214f3694"
},
{
"interview": false,
"hmNotification": true,
"isEditable": true,
"order": 1,
"hmStage": true,
"name": {
"en": "Pre-Screen"
},
"stageId": "51f0078d7297363f62059699"
},
{
"interview": false,
"hmNotification": false,
"hmStage": false,
"isEditable": true,
"order": 2,
"name": {
"en": "Phone Screen"
},
"stageId": "51d1a326c0d9887721778eae"
}]
Pythonスクリプトのサンプル: "タイプ":Pythonスクリプトを実行すると
import csv
cursor = db.workflows.find({}, {'_id': 1, 'stages.interview': 1, 'stages.hmNotification': 1, 'stages.hmStage': 1, 'stages.type':1, 'stages.isEditable':1, 'stages.order':1,
'stages.name':1, 'stages.stageId':1 })
flattened_records = []
for stages_record in cursor:
stages_record_id = stages_record['_id']
for stage_record in stages_record['stages']:
flattened_record = {
'_id': stages_record_id,
'stages.interview': stage_record['interview'],
'stages.hmNotification': stage_record['hmNotification'],
'stages.hmStage': stage_record['hmStage'],
'stages.type': stage_record['type'],
'stages.isEditable': stage_record['isEditable'],
'stages.order': stage_record['order'],
'stages.name': stage_record['name'],
'stages.stageId': stage_record['stageId']}
flattened_records.append(flattened_record)
、それはKeyError例外を示しています。スクリプトに不足しているフィールド名を追加する方法を教えてください。
作ることができる」stages.typ追加したときには非常によく働いた。:Pythonスクリプトで 『stage_record.get(』タイプ ')型の値は、CSVファイルに表示されます。大変ありがとうございます。 – user7070824
あなたの助けてくれてありがとう。どのように私は、文字、括弧、およびサブフィールドの名前をPythonで削除するのですか?ありがとう。 – user7070824