Introduction

The mongo shell is an interactive JavaScript interface to MongoDB. You can use the mongo shell to query and update data as well as perform administrative operations.

The mongo shell is a component of the MongoDB distributions. Once you have installed and have started MongoDB, connect the mongo shell to your running MongoDB instance.

Most examples in the MongoDB Manual use the mongo shell; however, many drivers provide similar interfaces to MongoDB.

Start the mongo Shell

IMPORTANT: Ensure that MongoDB is running before attempting to start the mongo shell.

To start the mongo shell and connect to your MongoDB instance running on localhost with default port:

  1. At a prompt in a terminal window (or a command prompt for Windows), go to your <mongodbinstallation dir>:

    cd <mongodb installation dir>
  2. Type ./bin/mongo to start mongo:
    ./bin/mongo

    If you have added the <mongodb installation dir>/bin to the PATH environment variable, you can just type mongo instead of ./bin/mongo.

Options

When you run mongo without any arguments, the mongo shell will attempt to connect to the MongoDB instance running on the localhost interface on port 27017. To specify a different host or port number, as well as other options, see examples of starting up mongo and mongo reference which provides details on the available options.

.mongorc.js File

When starting, mongo checks the user’s HOME directory for a JavaScript file named .mongorc.js. If found, mongointerprets the content of .mongorc.js before displaying the prompt for the first time. If you use the shell to evaluate a JavaScript file or expression, either by using the --eval option on the command line or by specifying a .js file to mongomongo will read the .mongorc.js file after the JavaScript has finished processing. You can prevent .mongorc.js from being loaded by using the --norc option.

Working with the mongo Shell

To display the database you are using, type db:

> db
test

The operation should return test, which is the default database. To switch databases, issue the use <db> helper, as in the following example:

> use mydb
switched to db mydb

To list the available databases, use the helper show dbs. See also db.getSiblingDB() method to access a different database from the current database without switching your current database context (i.e. db).

You can switch to non-existing databases. When you first store data in the database, such as by creating a collection, MongoDB creates the database. For example, the following creates both the databasemyNewDatabase and the collection myCollection during the insert() operation:

> use myNewDatabase
switched to db myNewDatabase
> db.myCollection.insert( { x: 1 } );
2016-11-30T22:43:53.953+0800 I COMMAND [conn3] command myNewDatabase.myCollection command: insert { insert: "myCollection", documents: [ { _id: ObjectId('583ee5a99efcdb65c8842e89'), x: 1.0 } ], ordered: true } ninserted:1 keyUpdates:0 writeConflicts:0 numYields:0 reslen:25 locks:{ Global: { acquireCount: { r: 2, w: 2 } }, Database: { acquireCount: { w: 1, W: 1 } }, Collection: { acquireCount: { W: 1 } } } protocol:op_command 280ms
WriteResult({ "nInserted" : 1 })

The db.myCollection.insert() is one of the methods available in the mongo shell

  • db refers to the current database.
  • myCollection is the name of the collection.

If the mongo shell does not accept the name of the collection, for instance if the name contains a space, hyphen, or starts with a number, you can use an alternate syntax to refer to the collection, as in the following:

> db["3test"].find()
>
> db.getCollection("3test").find()

For more documentation of basic MongoDB operations in the mongo shell, see:

Format Printed Results

The db.collection.find() method returns a cursor to the results; however, in the mongo shell, if the returned cursor is not assigned to a variable using the var keyword, then the cursor is automatically iterated up to 20 times to print up to the first 20 documents that match the query. The mongo shell will prompt Type it to iterate another 20 times.

To format the printed result, you can add the .pretty() to the operation, as in the following:

> db.myCollection.find().pretty()

In addition, you can use the following explicit print methods in the mongo shell:

  • print() to print without formatting
  • print(tojson(<obj>)) to print with JSON formatting and equivalent to printjson()
  • printjson() to print with JSON formatting and equivalent to print(tojson(<obj>))

For more information and examples on cursor handling in the mongo shell, see Iterate a Cursor in the mongo Shell. See also Cursor Help for list of cursor help in the mongo shell.

Multi-line Operations in the mongo Shell

If you end a line with an open parenthesis ('('), an open brace ('{'), or an open bracket ('['), then the subsequent lines start with ellipsis ("...") until you enter the corresponding closing parenthesis (')'), the closing brace ('}') or the closing bracket (']'). The mongo shell waits for the closing parenthesis, closing brace, or the closing bracket before evaluating the code, as in the following example:

> var x = 1
> var c = 0
> if (x > 0) {
... c++;
... }
0
> c
1

You can exit the line continuation mode if you enter two blank lines, as in the following example:

> if (x > 0
...
...
>

Tab Completion and Other Keyboard Shortcuts

The mongo shell supports keyboard shortcuts. For example,

  • Use the up/down arrow keys to scroll through command history. See .dbshell documentation for more information on the .dbshell file.

  • Use <Tab> to autocomplete or to list the completion possibilities, as in the following example which uses <Tab> to complete the method name starting with the letter 'c':

Exit the Shell

To exit the shell, type quit() or use the <Ctrl-c> shortcut.

MongoDB - Introduction of the mongo Shell的更多相关文章

  1. MongoDB - The mongo Shell, Write Scripts for the mongo Shell

    You can write scripts for the mongo shell in JavaScript that manipulate data in MongoDB or perform a ...

  2. MongoDB - The mongo Shell, mongo Shell Quick Reference

    mongo Shell Command History You can retrieve previous commands issued in the mongo shell with the up ...

  3. MongoDB - The mongo Shell, Data Types in the mongo Shell

    MongoDB BSON provides support for additional data types than JSON. Drivers provide native support fo ...

  4. MongoDB - The mongo Shell, Access the mongo Shell Help

    In addition to the documentation in the MongoDB Manual, the mongo shell provides some additional inf ...

  5. MongoDB - MongoDB CRUD Operations, Query Documents, Iterate a Cursor in the mongo Shell

    The db.collection.find() method returns a cursor. To access the documents, you need to iterate the c ...

  6. MongoDB基本增删改查操作-mongo shell

    基础 1.查看所有数据库: show dbs 2.选择数据库: use test 3.查看数据库中有哪些集合: show collections 如下图: 查询 1.查看集合中有哪些数据,其中abc为 ...

  7. 使用mongo shell和客户端连接至MongoDB Atlas

    MongoDB Atlas是Mongo官方的一个集群服务,也可以注册并创建一个免费的集群,但DB的大小只有500M,如果数据量不是很大的应用,可以选择该集群方案 需要注意的是,目前我使用的这个集群,服 ...

  8. MongoDB之Map-Reduce -- Mongo Shell版和C#版(上)

    最近有在学习MongoDB,看到了关于Map-Reduce,觉得蛮有意思的,所以在这里就记录下来作为学习笔记. 关于Map-Reduce的作用这里就引用一下官网以及另外一篇文章看到的,言简意赅. 1. ...

  9. MongoDB error: couldn't connect to server 127.0.0.1:27017 src/mongo/shell/mongo.js(转)

    rror: couldn't connect to server 127.0.0.1:27017 src/mongo/shell/mongo.js 一般这种情况就是:自己指定的数据库,所以不能.自动加 ...

随机推荐

  1. 响应式的dribbble作品集魔术布局展示效果

    在线演示1 本地下载 相信做设计的朋友肯定都知道dribbble.com,它是一个非常棒的设计师分享作品的网站,全世界数以万计的设计高手和行家都在这个网站上分享自己的作品,当然,如果你常在上面闲逛的话 ...

  2. Linux基础教程之/dev/null和/dev/zero的区别及其用法

    在Linux操作系统中/dev/null和/dev/zero是两个相似却又很特殊的文件,特别是在shell脚本开发和系统运维过程中会经常用这两个文件,因此作为Linux系统工程师,必须了解这两个文件的 ...

  3. 编写你自己的单点登录(SSO)服务

    王昱 yuwang881@gmail.com   博客地址http://yuwang881.blog.sohu.com 摘要:单点登录(SSO)的技术被越来越广泛地运用到各个领域的软件系统其中.本文从 ...

  4. 巧妙使用Jquery 改变元素的 onclick 事件

    需要点击图片将套组发布, 页面代码: <img width="20px" src=" <s:property value="IMAGES_PATH& ...

  5. Codeforces Round #253 (Div. 1) A. Borya and Hanabi 暴力

    A. Borya and Hanabi Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/442/p ...

  6. 分享:Android中利用机器码注册机制防止破解(转)

    转自:http://blog.csdn.net/huzgd/article/details/6684094 最近做一个Android应用时遇到这个问题,客户要求功能必须注册才能使用,而程序本身又不是联 ...

  7. cocos2d-html5的jsb模式下如何在编译时自动将js编译为jsc

    cocos2d-html5是一个用JS来开发游戏的框架,通过javascript Binding的方式可以将游戏编译到手机上.这对前端开发人员来说非常方便,开发效率也比使用c++开发要快的多. jsb ...

  8. Ildasm.exe 概要:

    一.前言: 微软的IL反编译实用程序——Ildasm.exe,可以对可执行文件(ex,经典的控制台Hello World 的 exe 可执行文件)抽取出 IL 代码,并且给出命名空间以及类的视图.在讲 ...

  9. FlatUI博皮制作

    Bootstrap3出来了,抛开内部框架结构和css命名的变化,bs3最大的改变莫过于扁平化. 扁平化UI中的典范,除了Metro,就是Flat了.目前本人FlatUI中毒中,于是开始慢慢的开始将博皮 ...

  10. 进程产生的三种方式:fork、system和exec

    1.fork()方式 fork()函数以父进程为蓝本复制一个进程,其ID号与父进程ID号不同.在Linux环境下,fork()是以写复制实现的,只有内存等与父进程不同,其他与父进程共享,只有在父进程或 ...