鍍金池/ 教程/ 數(shù)據(jù)庫/ 插入文檔
更新文檔
GridFS
Rockmongo 管理工具
Map Reduce
Java
創(chuàng)建備份
數(shù)據(jù)模型
創(chuàng)建數(shù)據(jù)庫
映射
查詢文檔
索引限制
ObjectId
刪除文檔
數(shù)據(jù)類型
高級索引
索引
優(yōu)勢
記錄排序
查詢分析
插入文檔
刪除集合
全文檢索
創(chuàng)建集合
概述
數(shù)據(jù)庫引用
覆蓋索引查詢
安裝環(huán)境
PHP
刪除數(shù)據(jù)庫
固定集合
關(guān)系
聚合
自動(dòng)增長
復(fù)制
限制記錄
部署
分片
正則表達(dá)式
原子操作

插入文檔

insert() 方法

要想將數(shù)據(jù)插入 MongoDB 集合中,需要使用 insert()save() 方法。

語法格式

insert() 方法的基本格式為:

>db.COLLECTION_NAME.insert(document)

范例 1

>db.mycol.insert({
   _id: ObjectId(7df78ad8902c),
   title: 'MongoDB Overview', 
   description: 'MongoDB is no sql database',
   by: 'tutorials point',
   url: 'http://www.tutorialspoint.com',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 100
})

mycol 是上一節(jié)所創(chuàng)建的集合的名稱。如果數(shù)據(jù)庫中不存在該集合,那么 MongoDB 會(huì)創(chuàng)建該集合,并向其中插入文檔。

在插入的文檔中,如果我們沒有指定 _id 參數(shù),那么 MongoDB 會(huì)自動(dòng)為文檔指定一個(gè)唯一的 ID。

_id 是一個(gè) 12 字節(jié)長的 16 進(jìn)制數(shù),這 12 個(gè)字節(jié)的分配如下:

_id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id, 3 bytes incrementer)

為了,你可以將用 insert() 方法傳入一個(gè)文檔數(shù)組,范例如下:

范例 2

>db.post.insert([
{
   title: 'MongoDB Overview', 
   description: 'MongoDB is no sql database',
   by: 'tutorials point',
   url: 'http://www.tutorialspoint.com',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 100
},
{
   title: 'NoSQL Database', 
   description: 'NoSQL database doesn't have tables',
   by: 'tutorials point',
   url: 'http://www.tutorialspoint.com',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 20, 
   comments: [  
      {
         user:'user1',
         message: 'My first comment',
         dateCreated: new Date(2013,11,10,2,35),
         like: 0 
      }
   ]
}
])

也可以用 db.post.save(document) 插入文檔。如果沒有指定文檔的 _id,那么 save() 就和 insert() 完全一樣了。如果指定了文檔的 _id,那么它會(huì)覆蓋掉含有 save() 方法中指定的 _id的文檔的全部數(shù)據(jù)。

上一篇:覆蓋索引查詢下一篇:GridFS