MongoDB常用操作

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
>



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章