I wrote a small js file that should list all the DBs in a current MongoDB instance and find a document in one of them (db = database, collection = col)

test.js

print(db.getMongo().getDBs())
db.getSiblingDB('database')
out = db.col.findOne()
print(out)

However, the output is

# mongo test.js

MongoDB shell version: 2.4.9
connecting to: test
[object Object]
null

What am I missing?

Cheers, M

有帮助吗?

解决方案

A few things:

printjson(db.getMongo().getDBs());
var db = db.getSiblingDB('database');
var out = db.col.findOne();
printjson(out);

You probably won't see the output you want unless you use printjson. Also .getSiblingDB() returns the database object, so you need to "set" the variable.

Finally, "always" use var to avoid the REPL "evaluating" each line. Which is also what you likely do not want.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top