Executing a MONGO query on the shell

Source: Internet
Author: User
Tags findone mongodb server

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.