DarkMatter in Cyberspace
  • Home
  • Categories
  • Tags
  • Archives

Run mongo Scripts in Shell


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:

  1. "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)
    })
    
  2. Use "print" function to print result to stdout.

  3. 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



Published

May 8, 2015

Last Updated

May 8, 2015

Category

Tech

Tags

  • mongodb 24
  • shell 46

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor