2016-11-12 63 views
1

我有一個數據庫有兩個集合。如何將此MongoDB數據導出爲CSV文件(兩個集合的「連接」)?

收集cars有看起來像這樣的文件:

{ license_number: "123456", name: "tesla" } 
{ license_number: "654321", name: "ford" } 
{ license_number: "987654", name: "volvo" } 

收集greatCars有看起來像這樣的文件:

{ license_number: "123456" } 

我要導出這兩個集合的「加入」到看起來像這樣的CSV文件:

license_number, name, isGreat 
123456,   tesla, TRUE 
654321,   ford, FALSE 
987654,   volvo, FALSE 

(請不要冒犯。這只是一個例子,我對汽車一無所知。)

+1

[這裏](http://stackoverflow.com/questions/31974925/how-can-i-work-with-join-to-export-data-from -mongodb) – khakishoiab

+0

@khakishoiab謝謝,把這個答案,我會接受它。 –

+0

爲您的便利我已經提出了一個答案。 – khakishoiab

回答

1

您可以創建一個簡短的JavaScript程序,將您想要導出的數據傳輸到可導出的新臨時集合中。

從CMD行創建一個文件export.js:

//initialise the export results collection 
    db.export.results.drop()`; 
    //create a cursor containing the contents of the list1 collection 
    cursor = db.list1.find(); 
     while (cursor.hasNext()) { 
      doc = cursor.next(); 
     //Check if the document exists in the list2 collection 
     list2 = db.list2.find({"<id_fieldname>": doc.<id_fieldname>}); 
     if (list2.hasNext()) { 
      //if it does exist, add the document from list1 to the new export collection 
      db.export.results.insert(doc); 
     } 
    } 
    print(db.export.results.count() + " matching documents found"); 

運行以下命令:

# mongo "localhost:27017/<dbname>" export.js 

它會創建一個名爲export.results含有從列表1集的文件與文件收集列表2(在您的案例carsgreatCars)收集與匹配的id字段。然後,您可以導出或轉儲這個集合:

# mongoexport --db <dbname> -c export.results -type csv -o <file_name>