mongo 学习二 mongodb shell操纵mongodb

3 篇文章 0 订阅
3 篇文章 0 订阅

一、进入shell

  mongo

二、显示当前的database

db

系统默认的database是test

三、显示所有的database

show dbs

四、切换database,uses <database>

uses admin

五、查询 db.<collection>.find() 

db.myname.find();

db["3test"].find()

db.getCollection("3test").find()
在有数字,引号等一些自负的collection时,要加[] 或用getCollection()取得
  • The find() method is the JavaScriptmethod to retrieve documents from<collection>. Thefind() method returns acursor to the results; however, in themongoshell, if the returned cursor is not assigned to a variable, then thecursor is automatically iterated up to 20 times to print up to thefirst 20 documents that match the query. The mongo shellwill promptType it to iterate another 20 times.

    You can set the DBQuery.shellBatchSize attribute to change thenumber of iteration from the default value20, as in thefollowing example which sets it to10:

    DBQuery.shellBatchSize = 10;
    

    For more information and examples on cursor handling in themongo shell, see Cursors.

    See also Cursor Help for list ofcursor help in the mongo shell.

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

Print

The mongo shell automatically prints the results of thefind() method if the returned cursoris not assigned to a variable. To format the result, you can add the.pretty() to the operation, as in the following:

db.<collection>.find().pretty()

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

  • print() to print without formatting
  • print(tojson(<obj>)) to print withJSON formatting andequivalent to printjson()
  • printjson() to print withJSON formatting and equivalentto print(tojson(<obj>))

Evaluate a JavaScript File

You can execute a .js file from within themongo shell,using theload() function, as in the following:

load("myjstest.js")

This function loads and executes the myjstest.js file.

The load() method accepts relative and absolute paths.If the current working directory of themongo shellis/data/db, and themyjstest.js resides in the/data/db/scripts directory, then the following calls withinthemongo shell would be equivalent:

load("scripts/myjstest.js")
load("/data/db/scripts/myjstest.js")

Note

There is no search path for the load()function. If the desired script is not in the current workingdirectory or the full specified path,mongo will not beable to access the file.

Use a Custom Prompt

You may modify the content of the prompt by creating the variableprompt in the shell. The prompt variable can hold strings as wellas any arbitrary JavaScript. Ifprompt holds a function that returns astring,mongo can display dynamic information in eachprompt. Consider the following examples:

Example

Create a prompt with the number of operations issued in the currentsession, define the following variables:

cmdCount = 1;
prompt = function() {
             return (cmdCount++) + "> ";
         }

The prompt would then resemble the following:

1> db.collection.find()
2> show collections
3>

Example

To create a mongo shell prompt in the form of<database>@<hostname>$ define the following variables:

host = db.serverStatus().host;

prompt = function() {
             return db+"@"+host+"$ ";
         }

The prompt would then resemble the following:

<database>@<hostname>$ use records
switched to db records
records@<hostname>$

Example

To create a mongo shell prompt that contains the systemup timeand the number of documents in the current database,define the following prompt variable:

prompt = function() {
             return "Uptime:"+db.serverStatus().uptime+" Documents:"+db.stats().objects+" > ";
         }

The prompt would then resemble the following:

Uptime:5897 Documents:6 > db.people.save({name : "James"});
Uptime:5948 Documents:7 >

Use an External Editor in the mongo Shell

New in version 2.2.

In the mongo shell you can use theedit operation toedit a function or variable in an external editor. Theeditoperation uses the value of your environmentsEDITOR variable.

At your system prompt you can define the EDITOR variable and startmongo with the following two operations:

export EDITOR=vim
mongo

Then, consider the following example shell session:

MongoDB shell version: 2.2.0
> function f() {}
> edit f
> f
function f() {
    print("this really works");
}
> f()
this really works
> o = {}
{ }
> edit o
> o
{ "soDoes" : "this" }
>

Note

As mongo shell interprets code edited in an externaleditor, it may modify code in functions, depending on theJavaScript compiler. Formongo may convert1+1 to2 or remove comments. The actual changes affect only theappearance of the code and will vary based on the version ofJavaScript used but will not affect the semantics of the code.

Exit the Shell

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


Access the mongo Shell Help Information

In addition to the documentation in the MongoDB Manual, the mongo shell provides some additionalinformation in its “online” help system. This document provides anoverview of accessing this help information.

Command Line Help

To see the list of options and help for starting the mongoshell, use the --help option from the command line:

mongo --help

Shell Help

To see the list of help, in the mongo shell, type help:

help

Database Help

  • To see the list of databases on the server, use the show dbscommand:

    show dbs
    

    New in version 2.4: show databases is now an alias for show dbs

  • To see the list of help for methods you can use on the dbobject, call the db.help() method:

    db.help()
    
  • To see the implementation of a method in the shell, type thedb.<method name> without the parenthesis (()), as in thefollowing example which will return the implementation of the methoddb.addUser():

    db.addUser
    

Collection Help

  • To see the list of collections in the current database, use theshow collections command:

    show collections
    
  • To see the help for methods available on the collection objects(e.g. db.<collection>), use the db.<collection>.help()method:

    db.collection.help()
    

    <collection> can be the name of a collection that exists,although you may specify a collection that doesn’t exist.

  • To see the collection method implementation, type thedb.<collection>.<method> name without the parenthesis (()),as in the following example which will return the implementation ofthe save() method:

    db.collection.save
    

Cursor Help

When you perform read operations withthe find() method in themongo shell, you can use various cursor methods to modifythe find() behavior and variousJavaScript methods to handle the cursor returned from thefind() method.

  • To list the available modifier and cursor handling methods, use thedb.collection.find().help() command:

    db.collection.find().help()
    

    <collection> can be the name of a collection that exists,although you may specify a collection that doesn’t exist.

  • To see the implementation of the cursor method, type thedb.<collection>.find().<method> name without the parenthesis(()), as in the following example which will return theimplementation of the toArray() method:

    db.collection.find().toArray
    

Some useful methods for handling cursors are:

  • hasNext() which checks whether thecursor has more documents to return.
  • next() which returns the next document andadvances the cursor position forward by one.
  • forEach(<function>) which iterates thewhole cursor and applies the <function> to each document returnedby the cursor. The <function> expects a single argument whichcorresponds to the document from each iteration.

For examples on iterating a cursor and retrieving the documents fromthe cursor, see cursor handling. Seealso Cursor for all available cursor methods.

Type Help

To get a list of the wrapper classes available in the mongoshell, such as BinData(), type help misc in themongo shell:

help misc


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值