Directing MongoDB Query Results to a File
November 21, 2013 2 Comments
The syntax for querying a MongoDB database and directing the results to a file is:
mongo server/database –eval "query" >> outputfile
where “server/database” is the address of the MongoDB database, “query” is the MongoDB command to execute, and “outputfile” is the file to which to direct the output.
Each of the following examples assumes that MongoDB has been installed in the C:\MongoDB folder.
Running this command…
C:\>mongodb\bin\mongo localhost/mydb –eval "db.docs.count()" >> counttest.txt
… will result in a file named counttest.txt that has contents similar to the following:
MongoDB shell version: 2.4.8
connecting to: localhost/mydb
1979179
For queries that will return JSON objects, be sure to wrap the command in the printjson() function, as in this example:
C:\>mongodb\bin\mongo localhost/mydb –eval "printjson(db.docs.findOne())" >> selectone.json
If the command is not wrapped by printjson, the resulting file will contain something like this:
MongoDB shell version: 2.4.8
connecting to: localhost/mydb
[object Object]
Notice that instead of the contents of the JSON object, the file simply contains the text [object Object]. However, if printjson is used, then the contents of the file will contain the actual JSON object, as shown here:
MongoDB shell version: 2.4.8
connecting to: localhost/mydb
{
"_id" : ObjectId("528b7c7b594d11167ecdd1a7"),
"leaf_num" : "0"
}
Here is an example that shows the use of a more complicated command. It performs an aggregation and returns the results as JSON (notice the use of printjson):
C:\>mongodb\bin\mongo localhost/mydb –eval "printjson(db.docs.group( { key: {scan_id: 1}, reduce: function(cur, result) {result.count += 1 }, initial: {count:0}}))" >> MongoCount.txt
For this example, the contents of the MongoCount.txt file are:
MongoDB shell version: 2.4.8
connecting to: localhost/mydb
[
{
"scan_id" : "01A23374-4D72-4A06-9B88-EF74D0ACEE5D",
"count" : 151
},
{
"scan_id" : "0245B979-D3D6-4B01-83E1-E8D1D2ADA255",
"count" : 250},
{
"scan_id" : "0330266.0001.002.umich.edu",
"count" : 164
},
{
"scan_id" : "03polybiblionrevue55sociuoft",
"count" : 290
}
]
you don’t use a dbs? how can i use one of the dbs before execute the query?
In the examples I have given, the names of the server and database against which to run the query are the first parameters specified. So in the command…
mongo localhost/mydb –eval “db.docs.count()” >> counttest.txt
…”localhost” is the name of the server, and “mydb” is the name of the database. There is no need to issue an explicit “use mydb” statement.