You can query a remote mongoDB with a mongo script, print output to stdout. Then manipulate the output data with other shell utilities.
For example, the following scripts get all fair names from a remote server, compare them with a local fair name set, to find out which are conflicted with the existing fair names in the local name.
Some key points:
-
"db" is a built-in global variable refers to the connected database, specified by the -h, -d options in mongo command line. It can be override by "connect" function. For example, with or without the first line, the script produce the same result when running
mongo test.js
:$ cat test.js // db = connect("localhost/test") print(db.getCollectionNames()) db.myCollection.find().forEach(function(item) { print(item.name) })
-
Use "print" function to print result to stdout.
-
To get command line arguments in mongo script, you must compose the evaluation string before(outside)
mongo
command, and you must add double quotes surrounding $exp.1 2 3 4 5 6 7 8 9 10
#!/bin/bash TargetDB=$1 TargetCol=$2 TargetField=$3 exp="db.${TargetCol}.find().forEach( function(item) \ { print(item.$TargetField); });" mongo localhost/$TargetDB --eval "$exp"
Ref:
Write Scripts for the mongo Shell
http://stackoverflow.com/questions/8971151/file-write-operations-in-mongo-script
http://stackoverflow.com/questions/14478304/redirect-output-of-mongo-query-to-a-csv-file