Chapter2: MongoDB

This section contain the following items:

  • 1.What is MongoDB?

  • 2.build MongoDB environment on Ubuntu (14.04)

  • 3.MongoDB debug message

  • 4.Backup and Restore

  • 5.Use mongoDb by using python

  • 6.MongoDB的基本操作

1.What is MongoDB?

2.build MongoDB environment on Ubuntu (14.04)

  1)echo “deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen" | sudo tee /etc/apt/sources.list.d/mongo.list:

  建立/etc/apt/sources.list.d/mongo.list,並寫入deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen(作為操作的一部分,APT使用一個檔案列出可獲得套裝軟體的鏡像站台位址件- /etc/apt/sources.list.d

檔案中的各項資訊通常按如下格式列出:deb http://host/debian distribution section1 section2 section3)

  2)sudo apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10:

    如果公鑰已經上傳到Key Server,可以使用下列指令下載公鑰:
      gpg --keyserver hkp://wwwkeys.us.pgp.net --recv-keys <金鑰指紋>

  3)sudo apt-get update:

    進行伺服器與用戶端的套件表頭清單更新, 在 apt-get update 後,再使用 apt-get dist-upgrade 這樣就能夠將整個系統升級

  4)sudo apt-get install mongodb-10gen

  5)ps -ef | grep mongo:

    確定 mongodb已在執行

  6)ls -ls /usr/bin | grep mongo

  7)ls -ls /etc/init.d | grep mongo

  8)sudo service mogodb start, sudo service mogodb stop, sudo service mogodb restart

3.MongoDB debug message

  1)ERROR: dbpath(data/db) does not exist

    sudo mkdir -p /data/db
    sudo useradd mongo
    sudo passwd mongo
    sudo chown -R mongo:mongo /data/db
    sudo chmod 0755 /data/db
    sudo chown -R $USER /data/db

    可以下ls -ld /data/db/
    ->理論上應該要是: drwxr-xr-x  7 gibber  wheel  238 Aug  5 11:07 /data/db/ (gibber是資料夾owner, wheel是gibber所屬的group)

   2)10309 Unable to create/open lock file: /data/db/mongod.lock errno:

    2014-10-06T12:59:35.802+0530 warning: Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused

    2014-10-06T12:59:35.802+0530 Error: couldn't connect to server 127.0.0.1:27017 (127.0.0.1), connection attempt failed at src/mongo/shell/mongo.js:146
exception: connect failed

    rm /var/lib/mongodb/mongod.lock
    sudo service mongod restart

    參考資料:
     1.http://stackoverflow.com/questions/26211671/failed-to-connect-to-127-0-0-127017-reason-errno111-connection-refused
    2.https://gist.github.com/adamgibbons/cc7b263ab3d52924d83b
    3.http://www.marcusoft.net/2014/05/mongodb-and-10309-unable-to-createopen.html
    4.http://stackoverflow.com/questions/24599119/mongodb-not-working-error-dbpath-data-db-does-not-exist

4.Backup and Restore

  Backup:
  1) Enter mongodb command mode by type "mongo" on terminal
  2) use admin
  3) db.runCommand({fsync:1,lock:1})
  4) db.currentOp()
  5) Ctrl + C to back to normal terminal mode 
  6) sudo mongodump -d vote -o ../data/backup
  7) Enter mongodb command mode by type "mongo" on terminal
  8) db.fsyncUnlock()

  Restore:
  1)sudo mongorestore -d vote --drop ../data/backup/vote

  reference:http://mongodbcanred.blogspot.tw/2015/01/mongodbmongodump-mongorestore.html

5.Use mongoDb by using python

   1)Install pymongo:
      import pymongo
      from pymongo import MongoClient
   2)Use monogoDb:
      client = MongoClient('localhost', 27017)
      db = client.{db name}
      collect = db[{collection name}]
      post1 = collect.find_one({"key": "value"})
      post1["key"]

6.MongoDB的基本操作

  • 與SQL的名詞對照

  • 與SQL指令的對照表

MongoDB

My SQL

新增

db.collection.find(條件)

select

修改

db.collection.insert(document)

insert

刪除

db.collection.update( criteria, objNew, upsert, multi )

update

查詢

db.collection.remove()

delete

  • 新增

  • 修改

  • 刪除

  • 查詢

    • find

      • db.collection.find(query, projection)

        • 定義: 從一個collection中找出documents,並回傳一個cursor物件

        • projection:

          • projection決定了哪些欄位要被回傳

        • cursor:

          • 一個指向a set of query的指標, 使用者可用迭代的方式從cursor取回查詢結果. 預設timeout為10分鐘

          • 取回方式

            • 1.手動迭代

              var myCursor = db.users.find( { type: 2 } );
              while (myCursor.hasNext(){
                print(tojson(myCursor.next()));
              }
              
              或是:
              
              var myCursor = db.users.find( { type: 2 } );
              while (myCursor.hasNext()) {
                 printjson(myCursor.next());
              }
              
              或是:
              
              var myCursor =  db.users.find( { type: 2 } );
              myCursor.forEach(printjson);
            • 2.轉為array

               var myCursor = db.inventory.find( { type: 2 } );
                var documentArray = myCursor.toArray();
                var myDocument = documentArray[3];
        • example:

          • 取出投過票的人

            collection.find({
              $or: [{
                  candidateId: {
                      $ne: 99
                  }
              }, {
                  candidateId2: {
                      $ne: 99
                  }
              }]
            }, {
              mail: 1
            }).toArray(function(err, items) {
                mongodb.close();
                  if (err) {
                    console.log("User.getVotedUsers:" + err);
                    callback(err);
                  }
                console.log(items);
                callback(null, items);
                //res.send(items);
            });
    • findOne

Last updated

Was this helpful?