【趙強老師】MongoDB插入文檔

MongoDB是非關係型數據庫NoSQL的表明,做爲一款可分佈式存儲的數據庫,對文檔的操做是MongoDB的重中之重。在本文中,咱們將着重爲你們介紹如何在MongoDB中插入文檔。mongodb

MongoDB一共爲咱們提供了三種方式用於插入文檔:數據庫

  • db.collection.insertOne() :插入一個指定文檔
  • db.collection.insertMany() :插入多個指定文檔
  • db.collection.insert() : 插入一個或多個指定文檔

使用insert語句能夠將一個新的文檔插入到一個collection中。若是該collection還不存在,insert語句會自動建立該collection。json

1、db.collection.insertOne() :插入一個指定文檔

db.collection.insertOne(
   <document>,
   {
      writeConcern: <document>
   }
)

示例:插入一條學生數據:數組

2、db.collection.insertMany() :插入多個指定文檔

db.collection.insertMany(
   [ <document 1> , <document 2>, ... ],
   {
      writeConcern: <document>,
      ordered: <boolean>
   }
)

上面的方法主要有三個參數:分佈式

  • document – 該參數指要插入的一個或多個文檔的數據,若是是一個文檔,則該參數爲一個json數據,如果多個文檔,則該參數是多個json數據組成的數組。
  • writeConcern – 可選參數,該參數指的是該次的插入操做的寫入關注程度,其值爲一個文檔,表現爲json數據。你們能夠參考前面的寫入關注的講解。
  • ordered – 2.6版本之後的新參數,可選參數。若是值爲true,則將數組中文檔的進行有序插入,若是一個文檔發生錯誤,mongodb將返回,而無需處理數組中的剩餘文檔。若是false,執行無序插入,若是錯誤發生在某個文檔中,則繼續處理數組中的剩餘文檔。默認爲true。

示例:spa

3、db.collection.insert() : 插入一個或多個指定文檔,即:insertOne和insertMany的統一

語法格式以下:code

db.collection.insert(
   <document or array of documents>,
   {
     writeConcern: <document>,
     ordered: <boolean>
   }
)

相關文章
相關標籤/搜索