轉自:http://www.mongoing.com/docs/tutorial/insert-documents.html
插入方法
MongoDB提供了如下方法向集合插入 文檔 documents :
本頁提供了 :program:在 mongo shell中插入操作的示例.
插入操作的行為表現
創建集合
插入的時候如果集合不存在,那么插入操作會創建集合。
_id 字段
在MongoDB中,存儲於集合中的每一個文檔都需要一個唯一的 _id 字段作為 primary_key。如果一個插入文檔操作遺漏了``_id`` 字段,MongoDB驅動會自動為``_id``字段生成一個 ObjectId。
這種情況同樣適用於通過帶有參數 upsert: true 的update操作來插入文檔的情況。
原子性
MongoDB中所有的寫操作在單一文檔層級上是原子的.更多關於MongoDB和原子性的信息,請參見 原子性和事務處理.
db.collection.insertOne()
3.2 新版功能.
db.collection.insertOne() 向集合插入 單個 文檔 document .
如下的示例向 users 集合插入了一個新的文檔。新的文檔有三個字段 name,``age``,和 status。 由於該文檔未指定 _id 字段,MongoDB 向該新文檔添加了值為 ObjectId 的 _id 字段。參見 插入操作的行為表現.
db.users.insertOne( { name: "sue", age: 19, status: "P" } )
You can run this method in the web shell below:
insertOne() 返回一個結果文檔,該結果文檔中列舉了插入文檔的``_id`` 字段值。 具體例子請參考::ref:<insertOne-examples>。
為了驗證插入了文檔,通過指定 _id 字段上的查詢過濾條件 query the collection:
db.users.find( { "name": "sue" } )
更多信息和例子請參考: db.collection.insertOne()。
db.collection.insertMany()
3.2 新版功能.
db.collection.insertMany() 向集合插入 多個 文檔。
如下的示例向 users 集合插入了三個新的文檔。每個文檔有三個字段 name,``age``和 status。由於這些文檔未指定 _id 字段,MongoDB 向每個新文檔添加了值為 ObjectId 的 _id 字段。 具體參見 插入操作的行為表現.
db.users.insertMany( [ { name: "bob", age: 42, status: "A", }, { name: "ahn", age: 22, status: "A", }, { name: "xi", age: 34, status: "D", } ] )
You can run this method in the web shell below:
insertMany() 將返回一個結果文檔,文檔中包含了每一個插入文檔的``_id``字段。 具體例子請參考 <insertMany-examples>。
驗證插入的文檔,可以參考 查詢集合:
db.users.find()
更多詳情和例子請參考: db.collection.insertMany()。
db.collection.insert()
db.collection.insert() 向集合插入一個或多個文檔.要想插入一個文檔,傳遞一個文檔給該方法;要想插入多個文檔,傳遞文檔數組給該方法.
如下的示例向 users 集合插入了一個新的文檔.新的文檔有三個字段 name,``age``,和 status.由於該文檔未指定 _id 字段,MongoDB 向該文檔添加了值為 ObjectId 的 _id 字段.參見 插入操作的行為表現.
db.users.insert( { name: "sue", age: 19, status: "P" } )
You can run this method in the web shell below:
db.collection.insert() 返回一個包含狀態信息的 WriteResult 對象。
該操作返回了含有操作狀態的 WriteResult 對象.插入文檔成功返回如下 WriteResult 對象:
WriteResult({ "nInserted" : 1 })
nInserted 字段指明了插入文檔的總數.如果該操作遇到了錯誤, WriteResult 對象將包含該錯誤信息.
如下的示例向 users 集合插入了多個文檔.由於這些文檔未指定 _id 字段,MongoDB 向每個新文檔添加了值為 ObjectId 的 _id 字段.參見 插入操作的行為表現.
db.users.insert( [ { name: "bob", age: 42, status: "A", }, { name: "ahn", age: 22, status: "A", }, { name: "xi", age: 34, status: "D", } ] )
該方法返回了包含操作狀態的 BulkWriteResult 對象.成功插入文檔返回如下 BulkWriteResult 對象:
BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 3, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] })
更多詳情和例子請參考: db.collection.insert()。
其他方法¶
以下方法也可以向集合中添加新文檔:
-
和``upsert: true``選項一起使用的 db.collection.updateOne()。
-
和``upsert: true`` 選項一起使用的 db.collection.updateOne().
-
和``upsert: true`` 選項一起使用的 db.collection.updateMany() .
-
和``upsert: true`` 選項一起使用的 db.collection.findAndModify() .
-
和``upsert: true`` 選項一起使用的 db.collection.findOneAndUpdate() .
-
和``upsert: true`` 選項一起使用的 db.collection.findOneAndReplace().
- db.collection.save().
- db.collection.bulkWrite().
