MongoDB之資料增加操作

stonebox1122發表於2017-08-24
只要是資料庫那麼就絕對離不開最為核心的功能:CRUD,所以在MongoDB裡面對於資料的操作也是支援的,但是需要提醒的是,除了增加之外,其它的都很麻煩。

1、資料增加
使用“db.集合.insert()”可以實現資料的增加操作。
範例:增加一個簡單資料
> use hr
switched to db hr
> db.info.insert({"url":""});
WriteResult({ "nInserted" : 1 })
> db.info.find();
{ "_id" : ObjectId("5990f8ea3268c8e84253ba3b"), "url" : "" }

範例:儲存陣列
> db.info.insert([{"url":""},{"url":""}])
BulkWriteResult({
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 2,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
> db.info.find();
{ "_id" : ObjectId("5990f8ea3268c8e84253ba3b"), "url" : "" }
{ "_id" : ObjectId("5990f97d3268c8e84253ba3c"), "url" : "" }
{ "_id" : ObjectId("5990f97d3268c8e84253ba3d"), "url" : "" }
如果想要儲存多個資料,那麼就使用陣列。

範例:儲存1000個資料
> for(var x=0;x<1000;x++){db.info.insert({"url":"stone_"+x});}
WriteResult({ "nInserted" : 1 })
> db.info.find();
{ "_id" : ObjectId("5990f8ea3268c8e84253ba3b"), "url" : "" }
{ "_id" : ObjectId("5990f97d3268c8e84253ba3c"), "url" : "" }
{ "_id" : ObjectId("5990f97d3268c8e84253ba3d"), "url" : "" }
{ "_id" : ObjectId("5990faea3268c8e84253ba3e"), "url" : "stone_0" }
{ "_id" : ObjectId("5990faea3268c8e84253ba3f"), "url" : "stone_1" }
{ "_id" : ObjectId("5990faea3268c8e84253ba40"), "url" : "stone_2" }
{ "_id" : ObjectId("5990faea3268c8e84253ba41"), "url" : "stone_3" }
{ "_id" : ObjectId("5990faea3268c8e84253ba42"), "url" : "stone_4" }
{ "_id" : ObjectId("5990faea3268c8e84253ba43"), "url" : "stone_5" }
{ "_id" : ObjectId("5990faea3268c8e84253ba44"), "url" : "stone_6" }
{ "_id" : ObjectId("5990faea3268c8e84253ba45"), "url" : "stone_7" }
{ "_id" : ObjectId("5990faea3268c8e84253ba46"), "url" : "stone_8" }
{ "_id" : ObjectId("5990faea3268c8e84253ba47"), "url" : "stone_9" }
{ "_id" : ObjectId("5990faea3268c8e84253ba48"), "url" : "stone_10" }
{ "_id" : ObjectId("5990faea3268c8e84253ba49"), "url" : "stone_11" }
{ "_id" : ObjectId("5990faea3268c8e84253ba4a"), "url" : "stone_12" }
{ "_id" : ObjectId("5990faea3268c8e84253ba4b"), "url" : "stone_13" }
{ "_id" : ObjectId("5990faea3268c8e84253ba4c"), "url" : "stone_14" }
{ "_id" : ObjectId("5990faea3268c8e84253ba4d"), "url" : "stone_15" }
{ "_id" : ObjectId("5990faea3268c8e84253ba4e"), "url" : "stone_16" }
Type "it" for more
> it
{ "_id" : ObjectId("5990faea3268c8e84253ba4f"), "url" : "stone_17" }
{ "_id" : ObjectId("5990faea3268c8e84253ba50"), "url" : "stone_18" }


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/28536251/viewspace-2144082/,如需轉載,請註明出處,否則將追究法律責任。

相關文章