MongoDB常用操作
首先,我們啟動mongoDB:
[root@h3 /]# mongod -f /etc/mongod.confWed Jul 24 23:38:58.195Wed 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.195about to fork child process, waiting until server is ready for connections.forked process: 14093all output going to: /var/log/mongo/mongod.logchild process started successfully, parent exiting[root@h3 /]#
然後,我們進入mongo shell:
[root@h3 /]# mongoMongoDB shell version: 2.4.5connecting to: testServer 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/32bitWed Jul 24 23:38:58.244 [initandlisten]>
在這裡,簡述以下mongo的shell有哪些功能:
1,具有功能完備的javascript解譯器;
2,可以完成任何javascript命令;
3,可以完成mongoDB操作管理命令,這些命令帶有強烈javascript風格。
例如,我們在shell中執行javascript 操作:
> var x = 100;> x / 333.333333333333336> x + 20120> x -4060>
來點更強大的:
> Math.sin(Math.PI / 2)1> function fac(n){... if (n <= 1){... return 1;... }... return n * fac(n - 1);... }> fac(5);120>
在MongoDB中切換資料庫:
> use foobarswitched to db foobar> use xyzswitched to db xyz> dbxyz>
在MongoDB中新增記錄。
在插入記錄時,MongoDB會檢查文檔是否包含_id,如果文檔沒有包含_id,MongoDB會為其建立。
> use blogswitched 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.insertfunction ( 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.confWed Jul 24 23:25:10.802Wed 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.802about to fork child process, waiting until server is ready for connections.forked process: 14043all output going to: /var/log/mongo/mongod.logERROR: 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 adminswitched to db admin> db.shutdownServer()Wed Jul 24 23:41:42.497 DBClientCursor::init call() failedserver should be down...Wed Jul 24 23:41:42.536 trying reconnect to 127.0.0.1:27017Wed Jul 24 23:41:42.539 reconnect 127.0.0.1:27017 failed couldn't connect to server 127.0.0.1:27017>