11

When I run this command in robomongo, I get a output with different rows:

 db.getCollection('houses').find({})

Now I tried to run the same command in the mongo shell:

I wrote a script mongo.js:

  conn = new Mongo();
  db = conn.getDB("development");

  db.getCollection('houses').find({});

Opened the console with:

  mongo --shell

And tried to run the command:

  > load('mongo.js')
  true

I do not understand why I get only true as output. I want to see the query output! What do I wrong? Thanks

John Smith
  • 6,105
  • 16
  • 58
  • 109

4 Answers4

38

In the shell script, instead of console.log you can use

print() // for plain texts,

or printjson() // for json

usage :

printjson(db.getCollection('houses').find({}));

codeofnode
  • 18,169
  • 29
  • 85
  • 142
6

When using

printjson(db.getCollection('houses').find({})); 

I get the output from the find object.

{
"_mongo" : connection to ***.***.***.***,
"_db" : *****,
"_collection" : ***.houses,
"_ns" : "*****.houses",
"_query" : {

},
"_fields" : null,
"_limit" : 0,
"_skip" : 0,
"_batchSize" : 0,
"_options" : 4,
"_cursor" : null,
"_numReturned" : 0,
"_special" : false,
"help" : function () {
print("find(<predicate>, <projection>) modifiers")
print("\t.sort({...})")
 ...........
}

if you use

db.getCollection('houses').find({}).forEach(printjson)

I get the desired output.

maskillbt
  • 61
  • 1
  • 3
0

An advancement for bigger scripts to keep the overview:

executeCommandAndLogResult(
    "Rename the collection",
    () =>
        db.getCollection('collection_a').renameCollection("collection_b")
);

function executeCommandAndLogResult(commandName, command) {
    printjson("--------------------------- Result of '" + commandName + "'-----------------------------")
    printjson(command());
    printjson("------------------------------ End of '" + commandName + "'-----------------------------")
}

The result will look like this if the renaming was successfull:

"--------------------------- Result of 'Rename the collection'-----------------------------"
{ "ok" : 1 }
"------------------------------ End of 'Rename the collection'-----------------------------"

Or like this if not:

"--------------------------- Result of 'Rename the collection'-----------------------------"
{
        "ok" : 0,
        "errmsg" : "source namespace does not exist",
        "code" : 26,
        "codeName" : "NamespaceNotFound"
}
"------------------------------ End of 'Rename the collection'-----------------------------"
RoBeaToZ
  • 1,113
  • 10
  • 18
0

Instead of using:

printjson(db.getCollection('houses').find({})); 

Use the findOne:

printjson(db.getCollection('houses').findOne({...})); 

Or, if you want to print multiple results, make sure to convert them to the array first:

printjson(db.getCollection('houses').find({}).toArray());