返回列表

mongodb 常用操作

默认分类 2014/04/17 06:25

原文地址:http://blog.csdn.net/yima1006/article/details/9879825

MongoDB常用操作

首先,我们启动mongoDB:

[root@h3 /]# mongod -f /etc/mongod.conf
Wed Jul 24 23:38:58.195
Wed Jul 24 23:38:58.195 warning: 32-bit servers don't have journaling enabled 
by default. Please use --journal if you want durability.
Wed Jul 24 23:38:58.195
about to fork child process, waiting until server is ready for connections.
forked process: 14093
all output going to: /var/log/mongo/mongod.log
child process started successfully, parent exiting
[root@h3 /]#

然后,我们进入mongo  shell:

[root@h3 /]# mongo
MongoDB shell version: 2.4.5
connecting to: test
Server has startup warnings:
Wed Jul 24 23:38:58.244 [initandlisten]
Wed Jul 24 23:38:58.244 [initandlisten] ** NOTE: This is a 32 bit MongoDB binary.
Wed Jul 24 23:38:58.244 [initandlisten] **       32 bit builds are limited to less than 2GB of data (or less with --journal).
Wed Jul 24 23:38:58.244 [initandlisten] **       Note that journaling defaults to off for 32 bit and is currently off.
Wed Jul 24 23:38:58.244 [initandlisten] **       See http://dochub.mongodb.org/core/32bit
Wed Jul 24 23:38:58.244 [initandlisten]
>

在这里,简述以下mongo的shell有哪些功能:

1,具有功能完备的javascript解释器;
2,可以完成任何javascript命令;
3,可以完成mongoDB操作管理命令,这些命令带有强烈javascript风格。
例如,我们在shell中执行javascript 操作:

> var x = 100;
> x / 3
33.333333333333336
> x + 20
120
> x -40
60
>

来点更强大的:

> Math.sin(Math.PI / 2)
1
> function fac(n){
... if (n <= 1){
...   return 1;
... }
... return n * fac(n - 1);
... }
> fac(5);
120
>

在MongoDB中切换数据库:

> use foobar
switched to db foobar
> use xyz
switched to db xyz
> db
xyz
>

在MongoDB中新增记录。

在插入记录时,MongoDB会检查文档是否包含_id,如果文档没有包含_id,MongoDB会为其创建。

> use blog
switched to db blog
> post = {'title' : 'My Blog Post', 'content': 'Here is my blog post.', 'date':new Date()}
{
        "title" : "My Blog Post",
        "content" : "Here is my blog post.",
        "date" : ISODate("2013-07-24T17:15:29.168Z")
}
> db.blog.insert(post)
> db.blog.find()
{ "_id" : ObjectId("51f00bbecd26ce7df43a2e86"), "title" : "My Blog Post", "content" : "Here is my blog post.", "date" : ISODate("2013-07-24T17:15:29.168Z") }
>

在这里,小述一下: "_id" 为系统默认增加的字段,用于唯一标示文档,类似于oracle中的rowid,ObjectId是Id的缺省产生办法,由12个字节(24个16进制数字)组成,第0-3字节为时间戳,第4-6字节为机器标示(一般是主机名的散列值),第7-8字节为pid,9-11字节为计数器。

读取数据:

> db.blog.findOne()
{
        "_id" : ObjectId("51f00bbecd26ce7df43a2e86"),
        "title" : "My Blog Post",
        "content" : "Here is my blog post.",
        "date" : ISODate("2013-07-24T17:15:29.168Z")
}
>

修改数据:

> post.comments = []
[ ]
> db.blog.update({title : 'My Blog Post'}, post)
> db.blog.find()
{ "_id" : ObjectId("51f00bbecd26ce7df43a2e86"), "title" : "My Blog Post", "content" : "Here is my blog post.", "date" : ISODate("2013-07-24T17:15:29.168Z"), "comments" : [ ] }
>

删除数据:

> db.blog.remove({title : 'My Blog Post'})
> db.blog.find()
>

寻求帮助:

> help
        db.help()                    help on db methods
        db.mycoll.help()             help on collection methods
        sh.help()                    sharding helpers
        rs.help()                    replica set helpers
        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 with time >= 1ms
        show logs                    show the accessible logger names
        show log [name]              prints out the last segment of log in memory, '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 further iterate
        DBQuery.shellBatchSize = x   set default number of items to display on shell
        exit                         quit the mongo shell
>

查看函数源码:

> db.blog.insert
function ( obj , options, _allow_dot ){
    if ( ! obj )
        throw "no object passed to insert!";
    if ( ! _allow_dot ) {
        this._validateForStorage( obj );
    }

    if ( typeof( options ) == "undefined" ) options = 0;

    if ( typeof( obj._id ) == "undefined" && ! Array.isArray( obj ) ){
        var tmp = obj; // don't want to modify input
        obj = {_id: new ObjectId()};
        for (var key in tmp){
            obj[key] = tmp[key];
        }
    }
    var startTime = (typeof(_verboseShell) === 'undefined' ||
                     !_verboseShell) ? 0 : new Date().getTime();
    this._mongo.insert( this._fullName , obj, options );
    this._lastID = obj._id;
    this._printExtraInfo("Inserted", startTime);
}
>

MongoDB在非正常关闭后,启动会出现以下错误:

[root@h3 ~]# mongod -f /etc/mongod.conf
Wed Jul 24 23:25:10.802
Wed Jul 24 23:25:10.802 warning: 32-bit servers don't have journaling enabled by default. Please use --journal if you want durability.
Wed Jul 24 23:25:10.802
about to fork child process, waiting until server is ready for connections.
forked process: 14043
all output going to: /var/log/mongo/mongod.log
ERROR: child process failed, exited with error number 100
[root@h3 ~]#

其原因是,MongoDB被锁定,在mongo的path目录下(本人的目录为/var/lib/mongo/)将mongod.lock删除,然后运行命令: mongod -repair  修复mongoDB,然后再启动。

PS:

正常关闭MongoDB的方法为:

进入 mongo shell ,运行如下命令:

> use admin
switched to db admin
> db.shutdownServer()
Wed Jul 24 23:41:42.497 DBClientCursor::init call() failed
server should be down...
Wed Jul 24 23:41:42.536 trying reconnect to 127.0.0.1:27017
Wed Jul 24 23:41:42.539 reconnect 127.0.0.1:27017 failed couldn't connect to server 127.0.0.1:27017
>