MongoDB中javascript指令碼編程簡介和入門執行個體_MongoDB

來源:互聯網
上載者:User

註:作者使用的mongodb版本為2.4.7。

入門例子

複製代碼 代碼如下:

conn = new Mongo();
db = conn.getDB("db-name");  //選擇資料庫
db.auth("user-name","password");  //使用者驗證

var map = function() {
    split_result = this.sentence.split(" ");
    for (var i in split_result) {
        var word = split_result[i].replace(/(^\s*)|(\s*$)/g,"").toLowerCase(); //去除了單詞兩邊可能的空格,並將單詞轉換為小寫
        if (word.length != 0) {
            emit(word, 1);
        }
    }
}

var reduce = function(key, values) {
    print(key+":"+Array.sum(values));
    return Array.sum(values);
}

db.data.mapReduce(
    map,
    reduce,
    {out:{merge:"mr_result"}}
)

儲存為test01.js,在終端中運行:

複製代碼 代碼如下:
$ mongo test01.js

運行結束後可以在集合mr_result中查看mapreduce結果。

值得注意的是,在js指令碼中如果直接:

複製代碼 代碼如下:
db.mr_result.find();

是無法輸出結果的。

應該使用下面的方式輸出結果:

複製代碼 代碼如下:
conn = new Mongo();
db = conn.getDB("db-name");  //選擇資料庫
db.auth("user-name","password");  //使用者驗證

var cursor = db.mr_result.find();

while(cursor.hasNext()) {
    r = cursor.next();
    print(r["_id"] + "\t" + r["value"]);
}


儲存為test02.js,運行:
複製代碼 代碼如下:
$ mongo test02.js

結果如下:
複製代碼 代碼如下:

a       1
code    1
collection      1
consider        1
contains        1
documents       1
error   1
follow  1
following       3
found   1
get     1
i       2
in      1
link    1
map-reduce      1
of      1
on      1
operations      1
orders  1
prototype       1
that    1
the     4
this    1
when    1

使用load()函數

load()函數用於引入其他檔案,這為代碼重用提供了便利。 最簡單的情形是,把資料庫連接操作的代碼放在一個單獨的檔案裡,在目前的目錄建立lib,在lib目錄下建立檔案base_operation.js,內容如下:

複製代碼 代碼如下:

function BaseOperation() {

    /*
    串連資料庫,返回連線物件
    */
    this.getDB = function() {
        conn = new Mongo();
        db = conn.getDB("db-name");
        db.auth("user-name","password");
        return db;
    }
}


在目前的目錄下建立檔案test03.js,內容如下:
複製代碼 代碼如下:

load("lib/base_operation.js");
BO = new BaseOperation();
db = BO.getDB();

var cursor = db.mr_result.find();

while(cursor.hasNext()) {
    r = cursor.next();
    print(r["_id"] + "\t" + r["value"]);
}


運行test03.js的效果和test02.js相同。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.