要想將數(shù)據(jù)插入 MongoDB 集合中,需要使用 insert()
或 save()
方法。
insert()
方法的基本格式為:
>db.COLLECTION_NAME.insert(document)
>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ù)組,范例如下:
>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ù)。