Demand
When writing gadgets, you often encounter the need to check things out of MongoDB, because you want to use it in conjunction with other bash toolchain, so the best way to do this is to execute the query on the shell and then pipe it to the next tool.
Scheme
Fortunately for MONGO to do is very convenient, only need to use MONGO--eval can. Example 1:
192.168. 1.2:27060'Printjson (Db.tasks.findOne ())'
This script first links the MongoDB server with the address 192.168.1.2:27060, and then executes the JavaScript in the quotation marks under the MyBase database, which is no different from the Mongoshell. It is worth noting that here is a global function of the Mongoshell Printjson used to convert the query results into JSON print.
Example 2:
192.168. 1.2:27060'db.tasks.find ({type: "Danger"}). ForEach (Printjson) '
When the query results are not unique, that is, instead of using FindOne to return a single result, as in Example 1, rather than returning a "result set", MONGO actually returns a cursor that can be traversed, if you use Printjson to wrap the query statement Printjson ( Db.find () ...) , the content of the cursor is actually printed. The correct approach is to foreach to traverse the cursor and print each item.
Summarize
Note the return content, which is typically a cursor that can be traversed.
Reference:
Http://stackoverflow.com/questions/4837673/how-to-execute-mongo-commands-through-shell-scripts
Executing a MONGO query on the shell