MongoDB 是一個基于分布式文件存儲的數(shù)據(jù)庫。由 C++ 語言編寫。旨在為 WEB 應(yīng)用提供可擴展的高性能數(shù)據(jù)存儲解決方案。
MongoDB 是一個介于關(guān)系數(shù)據(jù)庫和非關(guān)系數(shù)據(jù)庫之間的產(chǎn)品,是非關(guān)系數(shù)據(jù)庫當中功能最豐富,最像關(guān)系數(shù)據(jù)庫的。
本文給大家介紹MongoDB的插入文檔的方法,一起看看吧
1、文檔的數(shù)據(jù)存儲格式為BSON,類似于JSON。MongoDB插入數(shù)據(jù)時會檢驗數(shù)據(jù)中是否有“_id”,如果沒有會自動生成。
shell操作有insert和save兩種方法。當插入一條數(shù)據(jù)有“_id”值,并且現(xiàn)在集合中已經(jīng)有相同的值,使用insert插入時插入不進去,使用save時,會更新數(shù)據(jù)。
> db.student.drop()true> db.student.insert({"_id": 1, "name":"zhangsan", "age": 28})WriteResult({ "nInserted" : 1 })> db.student.find(){ "_id" : 1, "name" : "zhangsan", "age" : 28 }> db.student.insert({"_id": 1, "name":"zhangsan", "age": 27})WriteResult({"nInserted" : 0,"writeError" : {"code" : 11000,"errmsg" : "E11000 duplicate key error collection: zyhdb.student index: _id_ dup key: { : 1.0 }"}})> db.student.find(){ "_id" : 1, "name" : "zhangsan", "age" : 28 }> db.student.save({"_id": 1, "name":"zhangsan", "age": 27})WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })> db.student.find(){ "_id" : 1, "name" : "zhangsan", "age" : 27 }
2、批量插入,網(wǎng)上的文檔都說不能MongoDB不支持批量插入,現(xiàn)在試過可以,應(yīng)該是目前的版本支持批量插入了。
> db.student.insert([{"_id": 2, "name": "lisi"},{"_id": 3, "name": "wangwu"}, {"_id": 4, "name": "zhaoliu", "age": 28}])BulkWriteResult({"writeErrors" : [ ],"writeConcernErrors" : [ ],"nInserted" : 3,"nUpserted" : 0,"nMatched" : 0,"nModified" : 0,"nRemoved" : 0,"upserted" : [ ]})> db.student.find(){ "_id" : 1, "name" : "zhangsan", "age" : 27 }{ "_id" : , "name" : "lisi" }{ "_id" : , "name" : "wangwu" }{ "_id" : 4, "name" : "zhaoliu", "age" : 28 }
3、循環(huán)插入:
> for(var i=; i<; i++){db.fortest.insert({num: i})}WriteResult({ "nInserted" : })> db.fortest.find(){ "_id" : ObjectId("eceadaeabab"), "num" : 0}{ "_id" : ObjectId("eceadaeabab"), "num" : 1}{ "_id" : ObjectId("eceadaeabab"), "num" : 2}{ "_id" : ObjectId("eceadaeabab"), "num" : 3}{ "_id" : ObjectId("eceadaeabab"), "num" : 4}{ "_id" : ObjectId("eceadaeababa"), "num" : 5}{ "_id" : ObjectId("eceadaeababb"), "num" : 6}{ "_id" : ObjectId("eceadaeababc"), "num" : 7}{ "_id" : ObjectId("eceadaeababd"), "num" : 8}{ "_id" : ObjectId("eceadaeababe"), "num" : 9}
以上所述是小編給大家介紹的MongoDB快速入門筆記(三)之MongoDB插入文檔操作的相關(guān)知識,希望對大家有所幫助,更多精彩內(nèi)容,敬請關(guān)注武林網(wǎng)網(wǎng)站!
新聞熱點
疑難解答