MongoDB Shell 学习

MongoDB 自带一个JavaScript Shell可以从命令行与MongoDB进行交互。

运行MongoDB Shell :

cmd:

D:\MongoDB\mongodb-win32-i386-2.0.6\bin\mongo 运行,显示

D:\MongoDB\mongodb-win32-i386-2.0.6\bin>mongo
MongoDB shell version: 2.0.6
connecting to: test
>

可以输入 help 获取帮忙信息。

D:\MongoDB\mongodb-win32-i386-2.0.6\bin>mongo
MongoDB shell version: 2.0.6
connecting to: test
> help
        db.help()                    help on db methods
        db.mycoll.help()             help on collection methods
        rs.help()                    help on replica set methods
        help admin                   administrative help
        help connect                 connecting to a db help
        help keys                    key shortcuts
        help misc                    misc things to know
        help mr                      mapreduce

        show dbs                     show database names
        show collections             show collections in current database
        show users                   show users in current database
        show profile                 show most recent system.profile entries wit
h time >= 1ms
        show logs                    show the accessible logger names
        show log [name]              prints out the last segment of log in memor
y, 'global' is default
        use <db_name>                set current database
        db.foo.find()                list objects in collection foo
        db.foo.find( { a : 1 } )     list objects in foo where a == 1
        it                           result of the last line evaluated; use to f
urther iterate
        DBQuery.shellBatchSize = x   set default number of items to display on s
hell
        exit                         quit the mongo shell
>

 1. 运行简单的数学运算

> x=200
200
> x/5
40
> Math.sin(Math.PI /2)
1
> new Date("2010/1/1")
ISODate("2009-12-31T16:00:00Z")
"Hello,World!".replace("World","MongoDB");
Hello,MongoDB!

 2. 定义和调用javascript函数

function factorial(n) {
... if(n<=1) return 1;
... return n*factorial(n-1);
... }
> factorial(5)
120
>

 3. 创建使用数据库

创建了一个  foobar 数据库

> use foobar
switched to db foobar

通过命令查看一下当前数据库

> db
foobar

一看是 foobar 是我们要使用的数据库

再用命令查看一下系统中所有的数据库

> show dbs
local   (empty)

竟然没有,为什么呢?因为 只是创建了数据库 没有正在使用数据库 数据库MongoDB其实认为不存在,那我们进行存储数据吧

定义一个post对象

> post={"title":"My Blog Post","content":"Here's my blog post.","date":new Date()}

回车后显示对象内容

{
        "title" : "My Blog Post",
        "content" : "Here's my blog post.",
        "date" : ISODate("2012-06-15T09:22:44.953Z")
}

将对象插入数据库中,看到下面插入之前,系统还认为不存在foobar数据库,插入后就能看到foobar数据库了。

> show dbs
local   (empty)
> db
foobar
> db.blog.insert(post)
> show dbs
foobar  0.03125GB
local   (empty)
> db
foobar

find读取存储对象     find会返回集合中所有的文档 shell自动显示最多显示20个,可以继续获取更多进行查看更多文档。

> db.blog.find()
"_id" : ObjectId("4fdaff0b8f96acd2744b5086"), "title" : "My Blog Post""conte
nt
" : "Here's my blog post.""date" : ISODate("2012-06-15T09:22:44.953Z") }

findOne读取存储对象 findOne 只显示一个文档

> db.blog.findOne()
{
        "_id" : ObjectId("4fdaff0b8f96acd2744b5086"),
        "title" : "My Blog Post",
        "content" : "Here's my blog post.",
        "date" : ISODate("2012-06-15T09:22:44.953Z")
}

find 和 findOne 可以带 查询条件 进行查询文档。

4. 更新数据库的对象

给变量post增加 "comments" 键,注意更新时带限制条件(不然给所有的blog都更新了),并进行查看:

> post.comments=[]
[ ]
> db.blog.update({title:"My Blog Post"},post)
> db.blog.find()
"_id" : ObjectId("4fdaff0b8f96acd2744b5086"), "title" : "My Blog Post""conte
nt
" : "Here's my blog post.""date" : ISODate("2012-06-15T09:22:44.953Z"), "com
ments
" : [ ] }
> db.blog.findOne()
{
        "_id" : ObjectId("4fdaff0b8f96acd2744b5086"),
        "title" : "My Blog Post",
        "content" : "Here's my blog post.",
        "date" : ISODate("2012-06-15T09:22:44.953Z"),
        "comments" : [ ]
}

5. 删除对象

删除 也要带限制条件

> db.blog.remove({title:"My Blog Post"})
> db.blog.find()
> db.blog.findOne()
null

删除后已经查不到对象了

再查看数据库

> db
foobar
> show dbs
foobar  0.03125GB
local   (empty)

看到 foobar 数据库还是存在,虽然 已经没有数据库了,到底为什么呢?我们使用查看集合命令:

> show collections
blog
system.indexes
>

看到 blog 集合还存在 执行删除操作

> db.blog.drop()
true
> show collections
system.indexes
>

看到blog 集合 已经不存在了 ,也可以使用 命令进行删除 db.runCommand({"drop" : "blog"})  两者功能一样。

> db.runCommand({"drop":"blog"})
{
        "nIndexesWas" : 1,
        "msg" : "indexes dropped for collection",
        "ns" : "foobar.blog",
        "ok" : 1
}
> db.blog.findOne()
null
> show collections
system.indexes
>

 删除当前前数据库 db.dropDatabase()

> db
foobar
> db.dropDatabase()
"dropped" : "foobar""ok" : 1 }
> show dbs
local   (empty)
>

另一种方法也是删除当前数据库 db.runCommand({"dropDatabase": 1}); ,执行之前一定要用 db 看一下 当前数据库是什么,不要删除错了,后悔抓狂。。

 6. 一些使用技巧

 a. 了解函数功能,直接数据函数名称 不输入刮号和参数,这样就会显示函数的javascript源代码。比如我们想看看update的原理,或者看看参数的顺序和具体执行: 

> db.test.update
function (query, obj, upsert, multi) {
    assert(query, "need a query");
    assert(obj, "need an object");
    var firstKey = null;
    for (var k in obj) {
        firstKey = k;
        break;
    }
    if (firstKey != null && firstKey[0] == "$") {
        this._validateObject(obj);
    } else {
        this._validateForStorage(obj);
    }
    this._mongo.update(this._fullName, query, obj, upsert ? true : false, multi
true : false);
}
>

这些函数的具体代码可以访问 http://api.mongodb.org/js

b. 还有一些跟系统冲突的集合名

我们一般使用 db.集合名 的方式来访问集合,但是如果一个集合刚好是数据库类的一个属性,比如: db.version 就不行

> db.version
function () {
    return this.serverBuildInfo().version;
}
>

当函数在db中找不到属性时,才会将其作为集合查询返回。当属性和目标结合同名时,可以使用 getCollection 函数

> db.getCollection("version")
test.version
>

代码小技巧 既然 x.y 跟 x['y'] 等同 可以如下代码:

var collections = [ "posts" , "comments" , "authors" ];

for( i in collections ) {

             doStuff( db.blog[collections[i]] );

}

而不是 笨笨的写法调用 三遍;

doStuff( db.blog.posts ); 

doStuff( db.blog.comments); 

doStuff( db.blog.authors); 

原文地址:https://www.cnblogs.com/anan/p/2550553.html