Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File write operations in mongo script?

Tags:

mongodb

People also ask

What is write operation in MongoDB?

For each insert or delete write operation on a collection, MongoDB either inserts or removes the corresponding document keys from each index in the target collection. An update operation may result in updates to a subset of indexes on the collection, depending on the keys affected by the update.

Can we write queries in MongoDB?

MongoDB queries provide the simplicity in process of fetching data from the database, it's similar to SQL queries in SQL Database language. While performing a query operation, one can also use criteria or conditions which can be used to retrieve specific data from the database.

How do I run a Mongosh script?

Execute a Script From the Command Line. You can use mongosh to execute a script from the command line without entering the mongosh console. To specify the filename, use the --file or -f parameter to specify the filename. You may also need to specify connection information in addition to the --file or -f parameters.

Which operations are used to insert a document into a collection in MongoDB?

The insert() Method To insert data into MongoDB collection, you need to use MongoDB's insert() or save() method.


You could use print and then redirect output:

script.js:

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

then run the script and redirect output to a file:

mongo --quiet script.js > result.txt

http://www.mongodb.org/display/DOCS/Scripting+the+shell paragraph "Differences between scripted and interactive/ Printing".

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

Whenever I need to write the result of a mongo query to a local file I generally use the the writeFile(pathToFile, stringContents) function.

Example: let's say that you quickly need to find the email of all registered users and send it to your buddy Jim in the marketing department.

$ mongo mongodb://my-fancy-mongo-server --ssl -u fancy_username -p fancy_password 
successfully connected to my-fancy-mongo-server!
> emails = db.users.distinct('email_address')
> writeFile("jims_email_list.json", tojson(emails))

or if Jim expect's a CSV file then

$ mongo mongodb://my-fancy-mongo-server --ssl -u fancy_username -p fancy_password 
successfully connected to my-fancy-mongo-server!
> emails = db.users.distinct('email_address')
> writeFile("jims_email_list.csv", emails.join("\n"))

You can now send Jim the list of emails and save the day!

To important things to notice about the writeFile function:

  1. The second argument must be a string.
  2. The first argument must be a file that doesn't already exist, otherwise you will get an error.

You can skip the while loop using forEach():

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

Wouldn't it be simpler to use one of the Mongo drivers for a general purpose language (such as Python, Ruby, Java, etc) and write your results to a file that way, in a format you can use (such as CSV, etc.)?

UPDATE: According to the documentation for mongodump you can export a collection with a query:

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

However you would need to import that collection back into MongoDB to operate on it or use mongoexport to export as JSON or CSV using the same query flag (-q) as mongodump.