Print document value in mongodb shell

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); 
});

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