user7070824
user7070824

Reputation: 133

how to output the result to a file in monogodb

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.

Upvotes: 0

Views: 542

Answers (2)

satish chennupati
satish chennupati

Reputation: 2650

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

Upvotes: 2

Shishir Sonekar
Shishir Sonekar

Reputation: 410

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') )

Upvotes: 2

Related Questions