Print document value in mongodb shell

心不动则不痛 提交于 2020-08-22 12:37:51

问题


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.

enter image description here

Thanks in advance


回答1:


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

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



回答2:


db.collection.find() returns a cursor.

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,

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

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

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.

NOTES:

  • The db.collection.findOne() method returns a document (not a cursor).
  • Iterate a Cursor in the mongo Shell
  • Mongo Shell cursor methods



回答3:


To print each document when returning a cursor:

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



回答4:


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.



来源:https://stackoverflow.com/questions/25527617/print-document-value-in-mongodb-shell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!