10

当我在 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输出。我想看看查询输出!我错了什么?谢谢

4

4 回答 4

34

在 shell 脚本中,console.log你可以使用

print()// 对于纯文本,

printjson()// 对于 json

用法 :

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

于 2015-04-30T19:21:42.497 回答
6

使用时

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

我从 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)

我得到了想要的输出。

于 2017-07-18T10:00:14.543 回答
0

更大的脚本以保持概述的进步:

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'-----------------------------"
于 2020-08-12T08:57:20.753 回答
0

而不是使用:

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

使用 findOne:

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

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

printjson(db.getCollection('houses').find({}).toArray()); 
于 2021-08-25T22:28:38.687 回答