MongoDB快速入門學習筆記3 MongoDB的文檔插入操作

來源:互聯網
上載者:User

標籤:

1、文檔的資料存放區格式為BSON,類似於JSON。MongoDB插入資料時會檢驗資料中是否有“_id”域,如果沒有會自動產生。
shell操作有insert和save兩種方法。當插入一條資料有“_id”值,並且現在集合中已經有相同的值,使用insert插入時插入不進去,使用save時,會更新資料。

 1 > db.student.drop() 2 true 3 > db.student.insert({"_id": 1, "name":"zhangsan", "age": 28}) 4 WriteResult({ "nInserted" : 1 }) 5 > db.student.find() 6 { "_id" : 1, "name" : "zhangsan", "age" : 28 } 7 > db.student.insert({"_id": 1, "name":"zhangsan", "age": 27}) 8 WriteResult({ 9         "nInserted" : 0,10         "writeError" : {11                 "code" : 11000,12                 "errmsg" : "E11000 duplicate key error collection: zyhdb.student index: _id_ dup key: { : 1.0 }"13         }14 })15 > db.student.find()16 { "_id" : 1, "name" : "zhangsan", "age" : 28 }17 > db.student.save({"_id": 1, "name":"zhangsan", "age": 27})18 WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })19 > db.student.find()20 { "_id" : 1, "name" : "zhangsan", "age" : 27 }

 

2、批量插入,網上的文檔都說不能MongoDB不支援批量插入,現在試過可以,應該是目前的版本支援批量插入了。

 1 > db.student.insert([{"_id": 2, "name": "lisi"},{"_id": 3, "name": "wangwu"}, {"_id": 4, "name": "zhaoliu", "age": 28}]) 2 BulkWriteResult({ 3 "writeErrors" : [ ], 4 "writeConcernErrors" : [ ], 5 "nInserted" : 3, 6 "nUpserted" : 0, 7 "nMatched" : 0, 8 "nModified" : 0, 9 "nRemoved" : 0,10 "upserted" : [ ]11 })12 > db.student.find()13 { "_id" : 1, "name" : "zhangsan", "age" : 27 }14 { "_id" : 2, "name" : "lisi" }15 { "_id" : 3, "name" : "wangwu" }16 { "_id" : 4, "name" : "zhaoliu", "age" : 28 }

 

3、迴圈插入:

 1 > for(var i=0; i<10; i++){db.fortest.insert({num: i})} 2 WriteResult({ "nInserted" : 1 }) 3 > db.fortest.find() 4 { "_id" : ObjectId("57469e80142cea1d9aeabab5"), "num" : 0 } 5 { "_id" : ObjectId("57469e80142cea1d9aeabab6"), "num" : 1 } 6 { "_id" : ObjectId("57469e80142cea1d9aeabab7"), "num" : 2 } 7 { "_id" : ObjectId("57469e80142cea1d9aeabab8"), "num" : 3 } 8 { "_id" : ObjectId("57469e80142cea1d9aeabab9"), "num" : 4 } 9 { "_id" : ObjectId("57469e80142cea1d9aeababa"), "num" : 5 }10 { "_id" : ObjectId("57469e80142cea1d9aeababb"), "num" : 6 }11 { "_id" : ObjectId("57469e80142cea1d9aeababc"), "num" : 7 }12 { "_id" : ObjectId("57469e80142cea1d9aeababd"), "num" : 8 }13 { "_id" : ObjectId("57469e80142cea1d9aeababe"), "num" : 9 }

 

MongoDB快速入門學習筆記3 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.