新聞中心

因為 MongoDB 中沒有實現(xiàn)這個功能,所以我們需要通過編程的方式來實現(xiàn)。本節(jié)中我們將通過兩個集合(counters 和 tutorials)來實現(xiàn)自動遞增功能,其中 counters 集合用來記錄自動遞增的數(shù)值,tutorials 集合用來存儲具體的數(shù)據(jù)。
使用 counters 集合
假如有以下文檔,我們希望 _id 字段以 1、2、3、...、n 的自動遞增整數(shù)順序排列。
{
"_id":1,
"tutorials_name": "MongoDB 教程",
"url": "http://www.biancheng.net/mongodb/index.html",
"author": "編程幫"
}
為此,我們需要創(chuàng)建一個 counters 集合,并使用該集合來實現(xiàn)自動遞增的功能:
> db.createCollection("counters")
{ "ok" : 1 }
我們將在 counters 集合中插入以下文檔:
> db.counters.insert({_id:"productid",sequence_value:0})
WriteResult({ "nInserted" : 1 })
其中 _id 字段的值為 productid,sequence_value 字段的值默認為零,用來保存自動增長后的一個值。
創(chuàng)建 Javascript 函數(shù)
下面我們創(chuàng)建一個名為 getNextSequenceValue 的函數(shù),它能夠以序列名作為參數(shù),并將序列號遞增 1,然后返回更新后的序列號。
> function getNextSequenceValue(sequenceName){
... var sequenceDocument = db.counters.findAndModify(
... {
... query:{_id: sequenceName },
... update: {$inc:{sequence_value:1}},
... "new":true
... });
... return sequenceDocument.sequence_value;
... }
使用 Javascript 函數(shù)
下面我們創(chuàng)建一個新的集合,在向集合中插入數(shù)據(jù)時使用 getNextSequenceValue() 函數(shù)來定義 _id 字段的值,示例代碼如下:
> db.tutorials.insert({
... "_id":getNextSequenceValue("productid"),
... "tutorials_name": "MongoDB 教程",
... "url": "http://www.biancheng.net/mongodb/index.html",
... "author": "編程幫"
... })
WriteResult({ "nInserted" : 1 })
> db.tutorials.insert({
... "_id":getNextSequenceValue("productid"),
... "tutorials_name": "HTML 教程",
... "url": "http://www.biancheng.net/html/index.html",
... "author": "編程幫"
... })
WriteResult({ "nInserted" : 1 })
數(shù)據(jù)插入完成后,我們可以使用 find() 方法來查詢一下該集合中的數(shù)據(jù),以驗證我們是否使用 getNextSequenceValue() 函數(shù)成功的為集合中的 _id 字段設置自動遞增功能:
> db.tutorials.find().pretty()
{
"_id" : 1,
"tutorials_name" : "MongoDB 教程",
"url" : "http://www.biancheng.net/mongodb/index.html",
"author" : "編程幫"
}
{
"_id" : 2,
"tutorials_name" : "HTML 教程",
"url" : "http://www.biancheng.net/html/index.html",
"author" : "編程幫"
}分享標題:MongoDB自動增長的實現(xiàn)
標題來源:http://www.5511xx.com/article/cccggsi.html


咨詢
建站咨詢
