在 Mongodb 中登录到控制台

Log to console In Mongodb

当我 运行 在 robomongo 中执行此命令时,我得到了不同行的输出:

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

现在我尝试 运行 mongo shell 中的相同命令:

我写了一个脚本mongo.js:

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

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

打开控制台:

  mongo --shell

并尝试 运行 命令:

  > load('mongo.js')
  true

我不明白 为什么我只得到 true 作为输出。我想查看查询输出!我做错了什么?谢谢

在 shell 脚本中,您可以使用

而不是 console.log

print() // 对于纯文本,

printjson() // 对于 json

用法:

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

使用时

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

我从查找对象中得到输出。

{
"_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({...})")
 ...........
}

如果你使用

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

我得到了想要的输出。

更大脚本保持概览的进步:

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 + "'-----------------------------")
}

如果重命名成功,结果将如下所示:

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

如果没有也可以像这样:

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

而不是使用:

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

使用 findOne:

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

或者,如果要打印多个结果,请确保先将它们转换为数组:

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