2012-01-23 17 views
41

這是可以編寫查詢結果從蒙戈JS腳本文件。我搜查了很多,但我沒有找到任何解決方案。mongo腳本中的文件寫入操作?

例如: -

cursor = db.users.find(); 

while(cursor.hasNext()) { 
    cursor.next(); 
    // writing the cursor output to file ????<br/> 
} 
+1

順便說一句,如果你總是遍歷整個集合比它更有效地使用mongodump。使用腳本更加靈活,您可以在打印結果前進行各種處理。 – milan

+0

更多[mongodump(http://stackoverflow.com/questions/8991292/dump-mongo-collection-into-json-format) – averasko

回答

70

您可以使用打印,然後重定向輸出:

的script.js:

cursor = db.users.find(); 
while(cursor.hasNext()){ 
    printjson(cursor.next()); 
} 

然後運行該腳本,並將輸出重定向到一個文件:

mongo --quiet script.js > result.txt 
+1

是的,這是可能的。但我試圖運行腳本作爲守護進程。所以只有我要求進行文件寫入操作。謝謝。 – sudesh

+0

守護進程的輸出也可以被重定向到一個文件。你可以編寫一個shell腳本,在demo.js上調用mongo並重定向到一個文件。 – milan

+1

如何指定腳本應該使用的數據庫? – Nelu

3

那豈不是更簡單的使用Mongo drivers之一的通用語言(如Python和Ruby,Java的等),寫結果的文件方式,你可以使用的格式(如CSV等)?

UPDATE:根據對mongodump的文檔,你可以導出集合與查詢:

$ ./mongodump --db blog --collection posts 
-q '{"created_at" : { "$gte" : {"$date" : 1293868800000}, 
         "$lt" : {"$date" : 1296460800000} 
        } 
    }' 

但是你需要導入採集回的MongoDB來操作就可以了,或者使用mongoexport出口作爲JSON或CSV使用相同的查詢標誌(-q)作爲mongodump

+0

感謝您的回覆,但我想這是在使用蒙戈其中運行普通的js貝殼。 – sudesh

21

http://www.mongodb.org/display/DOCS/Scripting+the+shell款「的區別在腳本和交互/印刷之間「。

./mongo server.com/mydb --quiet --eval 「db.users.find()的forEach(printjson);」 > 1.txt的

+0

大把戲!沒有任何文件 – ruX

+0

如果你想在find )在這種情況下,最好在單獨的查詢文件中使用@milan的答案 – AndrewL

+0

@AndrewL你可以使用單引號嗎?我認爲這不應該做太多的轉義或什麼,對吧? – Erhannis

12

可以使用forEach()跳過while循環:

db.users.find().forEach(printjson); 
+7

更緊湊: db.users.find()。forEach(printjson); – AndrewL

2

對於不同的,你必須創建的script.js文件,其內容:

mongo = new Mongo("localhost"); 
doctor = mongo.getDB("doctor"); 
users = doctor.getCollection("users"); 
cities = users.distinct("address.city"); 
printjson(cities); 

然後在控制檯中運行:

mongo --quiet script.js > result.txt