1. 程式人生 > 實用技巧 >MongoDB學習筆記(一)-Insert操作

MongoDB學習筆記(一)-Insert操作

MongoDB插入

Insert Documents

  • menu
    • insert Behavior
    • insert Methods

插入行為

* 如果集合不存在,插入操作將建立集合。
* 在集合中,具有唯一主鍵`_id`。如果在插入檔案中未宣告`_id`;MongoDB將自動使用`ObjectIds`作為`_id`
  • 1
  • 2

插入資料的方法

MongoDB提供了儲存資料的方法一共有三個:

    1. db.collection.insertOne()
    2. db.collection.insertMany()
    3. db.collection.insert()
  • 1
  • 2
  • 3
  • 4
  • 5

db.collection.insertOne()

*3.2版本*
將單個文件插入到一個集合,
  • 1
  • 2
db.users.insertOne(
   {
      name: "sue",
      age: 19,
      status: "P"
   }
)
//會返回文件的操作狀態。
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5742045ecacf0ba0c3fa82b0")
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

db.collection.insertMany()

*3.2版本*
將文件陣列插入到一個集合,
  • 1
  • 2
db.users.insertMany(
   [
     { name: "bob", age: 42, status: "A", },
     { name: "ahn", age: 22, status: "A", },
     { name: "xi", age: 34, status: "D", }
   ]
)
//會返回文件的操作狀態。
{
   "acknowledged" : true,
   "insertedIds" : [
      ObjectId("57420d48cacf0ba0c3fa82b1"),
      ObjectId("57420d48cacf0ba0c3fa82b2"),
      ObjectId("57420d48cacf0ba0c3fa82b3")
   ]
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

db.collection.insert()

將單個或多個文件到一個集合。要插入一個單一的檔案,傳遞文件;插入多個檔案,傳遞文件陣列。
eg:
  • 1
  • 2
//插入單個物件
db.users.insert(
   {
      name: "sue",
      age: 19,
      status: "P"
   }
)
//返回一個 WriteResult 物件;如果插入錯誤,會返回錯誤資訊
WriteResult({ "nInserted" : 1 })

//插入陣列
db.users.insert(
   [
     { name: "bob", age: 42, status: "A", },
     { name: "ahn", age: 22, status: "A", },
     { name: "xi", age: 34, status: "D", }
   ]
)
//返回 BulkWriteResult 物件
BulkWriteResult({
   "writeErrors" : [ ],
   "writeConcernErrors" : [ ],
   "nInserted" : 3,
   "nUpserted" : 0,
   "nMatched" : 0,
   "nModified" : 0,
   "nRemoved" : 0,
   "upserted" : [ ]
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

同樣能實現插入效果的方法

  • db.collection.update() 當upsert為true時//第三個引數
  • db.collection.updateOne() 當upsert為true時//第三個引數
  • db.collection.updateMany() 當upsert為true時//第三個引數
  • db.collection.findAndModify() 當upsert為true時**
  • db.collection.findAndModify() 當upsert為true時**
  • db.collection.findOneAndReplace() 當upsert為true時
  • db.collection.save().
  • db.collection.bulkWrite().

db.collection.save()

db.collection.save(doc)若doc含有_id且在集合中存在,這將會替換集合內的文件(update),不存在則是insert該文件,若不存在_id,則是insert