File write operations in mongo script?

Is it possible to write the result of the request to a file from mongo js script. I searched a lot, but I did not find any solution.

eg: -

cursor = db.users.find(); while(cursor.hasNext()) { cursor.next(); // writing the cursor output to file ????<br/> } 
+40
mongodb
Jan 23 2018-12-12T00:
source share
5 answers

You can use print and then redirect the output:

script.js

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

then run the script and redirect the output to a file:

 mongo --quiet script.js > result.txt 
+68
Jan 23 2018-12-23T00:
source share

http://www.mongodb.org/display/DOCS/Scripting+the+shell item "Differences between Script and Interactive / Printing".

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

+21
Oct 11
source share

You can skip the while loop with forEach() :

 db.users.find().forEach(printjson); 
+12
Mar 14 '13 at 15:13
source share

Isn’t it easier to use one of Mongo drivers for a general-purpose language (for example, Python, Ruby, Java, etc.) and write the results to a file in such a way in a format that you can use (for example, in CSV, etc. .)?

UPDATE: According to the documentation for mongodump, you can export the collection with the request:

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

However, you will need to import this collection back into MongoDB to work, or use mongoexport to export as JSON or CSV using the same request flag ( -q ) as mongodump .

+3
Jan 23 2018-12-12T00:
source share

For different users, you need to create a script.js file with the contents:

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

then in the console do:

 mongo --quiet script.js > result.txt 
+1
Jun 08 '15 at 10:36
source share



All Articles