新聞中心
MongoDB 插入文檔
本章節(jié)中我們將向大家介紹如何將數(shù)據(jù)插入到 MongoDB 的集合中。

文檔的數(shù)據(jù)結(jié)構(gòu)和 JSON 基本一樣。
所有存儲(chǔ)在集合中的數(shù)據(jù)都是 BSON 格式。
BSON 是一種類似 JSON 的二進(jìn)制形式的存儲(chǔ)格式,是 Binary JSON 的簡(jiǎn)稱。
插入文檔
MongoDB 使用 insert() 或 save() 方法向集合中插入文檔,語(yǔ)法如下:
db.COLLECTION_NAME.insert(document) 或 db.COLLECTION_NAME.save(document)
- save():如果 _id 主鍵存在則更新數(shù)據(jù),如果不存在就插入數(shù)據(jù)。該方法新版本中已廢棄,可以使用 db.collection.insertOne() 或 db.collection.replaceOne() 來(lái)代替。
- insert(): 若插入的數(shù)據(jù)主鍵已經(jīng)存在,則會(huì)拋 org.springframework.dao.DuplicateKeyException 異常,提示主鍵重復(fù),不保存當(dāng)前數(shù)據(jù)。
3.2 版本之后新增了 db.collection.insertOne() 和 db.collection.insertMany()。
db.collection.insertOne() 用于向集合插入一個(gè)新文檔,語(yǔ)法格式如下:
db.collection.insertOne(, { writeConcern: } )
db.collection.insertMany() 用于向集合插入一個(gè)多個(gè)文檔,語(yǔ)法格式如下:
db.collection.insertMany( [, , ... ], { writeConcern: , ordered: } )
參數(shù)說(shuō)明:
- document:要寫(xiě)入的文檔。
- writeConcern:寫(xiě)入策略,默認(rèn)為 1,即要求確認(rèn)寫(xiě)操作,0 是不要求。
- ordered:指定是否按順序?qū)懭?,默認(rèn) true,按順序?qū)懭搿?/li>
實(shí)例
以下文檔可以存儲(chǔ)在 MongoDB 的 runoob 數(shù)據(jù)庫(kù) 的 col 集合中:
>db.col.insert({title: 'MongoDB 教程',
description: 'MongoDB 是一個(gè) Nosql 數(shù)據(jù)庫(kù)',
by: '菜鳥(niǎo)教程',
url: 'http://www.runoob.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100
})
以上實(shí)例中 col 是我們的集合名,如果該集合不在該數(shù)據(jù)庫(kù)中, MongoDB 會(huì)自動(dòng)創(chuàng)建該集合并插入文檔。
查看已插入文檔:
> db.col.find()
{ "_id" : ObjectId("56064886ade2f21f36b03134"), "title" : "MongoDB 教程", "description" : "MongoDB 是一個(gè) Nosql 數(shù)據(jù)庫(kù)", "by" : "菜鳥(niǎo)教程", "url" : "http://www.runoob.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }
>
我們也可以將數(shù)據(jù)定義為一個(gè)變量,如下所示:
> document=({title: 'MongoDB 教程',
description: 'MongoDB 是一個(gè) Nosql 數(shù)據(jù)庫(kù)',
by: '菜鳥(niǎo)教程',
url: 'http://www.runoob.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100
});
執(zhí)行后顯示結(jié)果如下:
{
"title" : "MongoDB 教程",
"description" : "MongoDB 是一個(gè) Nosql 數(shù)據(jù)庫(kù)",
"by" : "菜鳥(niǎo)教程",
"url" : "http://www.runoob.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}
執(zhí)行插入操作:
> db.col.insert(document)
WriteResult({ "nInserted" : 1 })
>
插入文檔你也可以使用 db.col.save(document) 命令。如果不指定 _id 字段 save() 方法類似于 insert() 方法。如果指定 _id 字段,則會(huì)更新該 _id 的數(shù)據(jù)。
網(wǎng)站題目:創(chuàng)新互聯(lián)MongoDB教程:MongoDB插入文檔
瀏覽路徑:http://www.5511xx.com/article/cdjiccp.html


咨詢
建站咨詢
