MongoDB資料庫中更新與刪除資料

來源:互聯網
上載者:User

標籤:array   現在   name   刪除   參數   multi   建立資料庫   整數   lin   

MongoDB資料庫中更新與刪除資料

在MongoDB資料庫中,可以使用Collection對象的update方法更新集合中的資料文檔。使用方法如下所示:

collection.update(selector, document, [options], [callback]);

selector參數:該參數值為一個對象,用於查詢需要更新的資料文檔。該參數值指定的方法和我們前面使用的find方法中使用的selector參數值的指定方法完全相同。

document參數:該參數值為一個對象,用於指定用來更新的資料文檔。

options參數:該參數值為一個對象,用於指定更新資料時使用的選項,下面介紹幾個常用的選項屬性:
  1. upsert 該屬性值是一個布爾值,用於指定是否在跟新資料時執行upsert操作,所謂upsert操作是指當被更新的資料文檔不存在時插入一條資料
文檔的操作。該屬性值預設為false。

  2. multi: 該屬性值也是一個布爾值,用於指定是否更新所有符合查詢條件的資料文檔。預設值為false(只更新第一條符合查詢條件的資料文檔)。

callback參數:用於指定更新資料操作執行結束時執行的回呼函數,該回呼函數的指定方法如下所示:

function(err, result){};

err參數為更新資料操作失敗時拋出的錯誤對象,result參數值為一個整數值,代表成功更新的資料條數,當更新資料操作失敗時該屬性值為null。

首先我們還是一樣先查看資料庫中users集合中的所有資料如下,使用代碼如下:

const mongo = require(‘mongodb‘);const Server = mongo.Server;const Db = mongo.Db;const server = new Server(‘localhost‘, ‘27017‘, { auto_reconnect: true });const db = new Db(‘dataDb‘, server, { safe: true });db.open(function(err, db) {  if (err) {    throw err;  } else {    console.log(‘成功建立資料庫連接‘);    db.collection(‘users‘, function(err, collection) {      if (err) {        throw err;      } else {        // 開始查詢集合users        collection.find({}).toArray(function(err, docs) {          if (err) {            throw err;          } else {            console.log(docs);            db.close();          }        });      }    });  }});

如所示:

然後現在我們使用update方法來更新上面的資料,我想把 userName=‘空智‘的資料更新成‘龍恩0707‘,使用方法如下:

collection.update({}, {userName: ‘龍恩0707‘});

如下所有的代碼:

const mongo = require(‘mongodb‘);const Server = mongo.Server;const Db = mongo.Db;const server = new Server(‘localhost‘, ‘27017‘, { auto_reconnect: true });const db = new Db(‘dataDb‘, server, { safe: true });db.open(function(err, db) {  if (err) {    throw err;  } else {    console.log(‘成功建立資料庫連接‘);    db.collection(‘users‘, function(err, collection) {      if (err) {        throw err;      } else {        // 開始查詢集合users        collection.update({}, {userName: ‘龍恩0707‘}, function(err, result) {          if (err) {            throw err;          } else {            collection.find({}).toArray(function(err, docs) {              if (err) {                throw err;              } else {                console.log(‘更新後的資料:‘);                console.log(docs);                db.close();              }            });          }        })      }    });  }});

執行運行結果如下所示:

如上可以看到只更新了第一條資料,那是因為options對象中的屬性multi預設為false,如果需要更改所有的資料的話,需要指定options中的multi屬性為true即可。需要在document參數值對象中使用$set原子操作符。

如下更改代碼:

collection.update({}, {$set: {userName: ‘龍恩0707‘}}, {multi: true}, function(err, result) {});

如下所有代碼:

const mongo = require(‘mongodb‘);const Server = mongo.Server;const Db = mongo.Db;const server = new Server(‘localhost‘, ‘27017‘, { auto_reconnect: true });const db = new Db(‘dataDb‘, server, { safe: true });db.open(function(err, db) {  if (err) {    throw err;  } else {    console.log(‘成功建立資料庫連接‘);    db.collection(‘users‘, function(err, collection) {      if (err) {        throw err;      } else {        // 開始查詢集合users        collection.update({}, {$set: {userName: ‘龍恩0707‘}}, {multi: true}, function(err, result) {          if (err) {            throw err;          } else {            collection.find({}).toArray(function(err, docs) {              if (err) {                throw err;              } else {                console.log(‘更新後的資料:‘);                console.log(docs);                db.close();              }            });          }        })      }    });  }});

運行結果如下:

3. 理解options對象中的upsert屬性
如果將options參數值對象中的upsert屬性值指定為true,那麼會當集合中不存在符合查詢條件的資料文檔時,會將把document參數值對象插入到集合中。
現在我們再來看看在update方法中更新一條userName欄位為 ‘aaa‘的資料文檔,users集合中不存在該資料文檔的,他會將把update方法中指定
document參數值對象插入到users集合中。如下代碼:

collection.update({userName: ‘aaa‘}, {userName: ‘aaa‘}, {upsert: true}, function(err, result) {});

執行結果如下所示:

可以看到在視窗中顯示users集合中被插入一條資料aaa;

4. remove()方法刪除集合中的資料文檔
該方法是刪除集合中的資料文檔,該方法使用如下所示:

collection.remove([selector], [options], [callback]);

selector參數用於查詢需要刪除的資料文檔。
options參數值為一個對象,用於指定刪除資料時使用的選項. 常用的選項屬性值如下:
single: 屬性值為一個布爾值,用於指定是否只刪除第一條滿足查詢條件的資料文檔,預設屬性值為false。

callback參數用於指定更新資料操作執行結束時執行的回呼函數,該回呼函數指定的方法如下所示:

function(err, result) {}

err參數為刪除資料操作失敗時拋出的錯誤對象。result參數值為一個整數值,代表成功刪除的資料條數,當刪除資料失敗時該屬性值為null.

如下的demo,首選往goods這個集合中插入資料後,然後在刪除前查詢下資料有多少,查詢完成後,繼續執行刪除操作,刪除條件就是所有 price
為11的都刪除掉;如下所有代碼所示:

const mongo = require(‘mongodb‘);const Server = mongo.Server;const Db = mongo.Db;const server = new Server(‘localhost‘, ‘27017‘, { auto_reconnect: true });const db = new Db(‘dataDb‘, server, { safe: true });var docs = [  {type: ‘food‘, price: 11},  {type: ‘food‘, price: 10},  {type: ‘food‘, price: 9},  {type: ‘food‘, price: 8},  {type: ‘food‘, price: 7},];db.open(function(err, db) {  if (err) {    throw err;  } else {    console.log(‘成功建立資料庫連接‘);    db.collection(‘goods‘, function(err, collection) {      collection.insert(docs, function(err, docs) {        if (err) {          throw err;        } else {          collection.find({}).toArray(function(err, docs) {            if (err) {              throw err;            } else {              console.log(‘刪除前的goods集合中的資料為如下:‘);              console.log(docs);            }          });        }      });      collection.remove({price: 11}, function(err, result) {        if (err) {          throw err;        } else {          collection.find({}).toArray(function(err, docs) {            if (err) {              throw err;            } else {              console.log(‘刪除後的資料為:‘);              console.log(docs);              db.close();            }          });        }      });    });  }});

如所示:

由於options參數對象中的single屬性值預設為false,因此將刪除所有滿足查詢條件的資料文檔,如果將該屬性值設定為true,那麼將只刪除第一條滿足條件的資料文檔。如下代碼:

collection.remove({price: 10}, {single: true}, function(err, result) {});

如所示

5. findAndRemove方法查詢並刪除一條資料文檔
使用該方法可以查詢並刪除一條資料文檔,該方法使用方式如下所示:

collection.findAndRemove(selector, sort, [options], callback);

selector參數值為一個對象,用於查詢需要刪除的資料文檔;
sort參數值為一個數組,用於指定當存在多條符合查詢條件的資料文檔時這些資料的排序方式。該數組包含兩個元素,每個元素都為一個數組,
第一個元素值為用於排序的欄位名,第二個元素值可以為1或-1,1 是升序, -1是降序。
options值為一個對象,用於指定刪除資料時使用的選項屬性。
callback參數 用於指定刪除資料操作時結束執行的回呼函數,該回呼函數指定方法如下所示:

function(err, doc) {}

err參數值為刪除資料操作失敗時拋出的錯誤對象。
doc參數值為一個對象,代表刪除的資料文檔,當刪除資料失敗時該屬性值為null。

MongoDB資料庫中更新與刪除資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.