在 mongodb shell 中打印文档值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25527617/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 20:07:58  来源:igfitidea点击:

Print document value in mongodb shell

mongodbmongodb-query

提问by kchromik

I want to print the value for this JSON document in the mongo shell. Like a simple console output, without creating a new collection or document.

我想在 mongo shell 中打印此 JSON 文档的值。就像一个简单的控制台输出,无需创建新的集合或文档。

enter image description here

在此处输入图片说明

Thanks in advance

提前致谢

回答by kchromik

I found a solution, by using .forEach()to apply a JavaScript method:

我找到了一个解决方案,通过使用.forEach()来应用 JavaScript 方法:

db.widget.find(
    { id : "4" }, 
    {quality_level: 1, _id:0}
).forEach(function(x) { 
    print(x.quality_level); 
});

回答by prasad_

db.collection.find()returns a cursor.

db.collection.find()返回一个游标

There are a bunch of methods for the cursor object which can be used to get the cursor information, iterate, get and work with the individual documents from the query result (in the Mongo Shell). For example,

游标对象有很多方法可用于从查询结果(在 Mongo Shell 中)获取游标信息、迭代、获取和处理单个文档。例如,

let result = db.widget.find( { id : "4" }, { quality_level: 1, _id: 0 } );

The methods print, printjsonand tojsonare useful for printing the query results assigned to a cursor and iterated over it, in the Mongo Shell.

的方法printprintjsontojson用于打印分配给光标和遍历它,在蒙戈壳牌查询结果是有用的。

In this particular example, each of the following statements will print the expected output:

在此特定示例中,以下每个语句都将打印预期输出:

    result.forEach( doc =>  print( doc.quality_level ) );
    result.forEach( doc =>  print( tojson(doc)) );
    result.forEach( printjson );

Note the query must be run each time the cursor is to be iterated, as the cursor gets closed after iterating thru it. But, one can use the cursor.toArray()method to get a JavaScript array, and iterate the array and work with the query result documents without running the query again.

请注意,每次迭代游标时都必须运行查询,因为游标在迭代后关闭。但是,可以使用该cursor.toArray()方法获取JavaScript 数组,并迭代该数组并处理查询结果文档,而无需再次运行查询。

NOTES:

笔记:

回答by Luke W

To print each document when returning a cursor:

要在返回光标时打印每个文档:

db.widget.find().forEach(printjson);

回答by Markus W Mahlberg

db.widget.findOne({"id":4},{quality_level:1,_id:0}).quality_level

The projection is not necessary for this to work, but it reduces the data which is to be transferred in case of a sharded collection.

投影对于此工作不是必需的,但它减少了在分片集合的情况下要传输的数据。