0

I wan to list all database in Monogodb and output to a txt file, but it did not work.

mongo 127.0.0.1/test -eval 'var c= show databases;' >>db_list.txt

the error message is

MongoDB shell version: 2.6.12
connecting to: 127.0.0.1/test
2016-12-06T12:12:32.456-0700 SyntaxError: Unexpected identifier

anyone knows how to make this work. I appreciate any help.

user7070824
  • 133
  • 1
  • 2
  • 11

2 Answers2

2

To use eval and list databases directly on a shell, the following query should be helpful.

mongo test --eval "printjson(db.adminCommand('listDatabases'))"
MongoDB shell version: 3.2.10
connecting to: test
{
        "databases" : [
                {
                        "name" : "local",
                        "sizeOnDisk" : 73728,
                        "empty" : false
                },
                {
                        "name" : "m034",
                        "sizeOnDisk" : 11911168,
                        "empty" : false
                },
                {
                        "name" : "test",
                        "sizeOnDisk" : 536576,
                        "empty" : false
                }
        ],
        "totalSize" : 12521472,
        "ok" : 1
}

This will list all the collection names in a particular DB.

mongo test --eval "printjson(db.getCollectionNames())"
MongoDB shell version: 3.2.10
connecting to: test
[
        "aaa",
        "areamodel",
        "email",
        "hex",
        "key",
        "mel",
        "multi",
        "ques",
        "rich"
]

A sample execution for reference (screenshot) A sample execution for reference

satish chennupati
  • 2,602
  • 1
  • 18
  • 27
  • thanks, it worked on Linux. the command is mongo 127.0.0.1 -eval "var c= printjson(db.adminCommand('listDatabases'))" >>db_list.txt . @satish chennupati, thanks so much. – user7070824 Dec 06 '16 at 20:10
  • happy to help my friend. :D – satish chennupati Dec 06 '16 at 20:11
  • I am not a big fan of using image in an answer. It simply does not add any value. Instead you should copy/paste your code. – styvane Dec 07 '16 at 05:32
  • @styvane it was spur of the moment. will try to avoid pasting images as answers from next time. Rather i would add code first and can later append an image as an example if needed. – satish chennupati Dec 07 '16 at 12:23
  • You can start by editing the answer. You already said something like that [here](http://stackoverflow.com/questions/40896625/retrieve-field-value-from-array-of-sub-document/40897012?noredirect=1#comment69008123_40897012) but did not delete the answer. – styvane Dec 07 '16 at 13:51
  • thanks for your updated solution . @ satish chennupati. thanks – user7070824 Dec 07 '16 at 16:41
2

Instead of test you can go simply, mongo db_name query.js > out.json

here query.js contains any query like: printjson( db.adminCommand('listDatabases') )

Shishir Sonekar
  • 410
  • 1
  • 3
  • 15