Blog

Chèn Document trong MongoDB

Phương thức insert() trong MongoDB

Để chèn dữ liệu vào trong Collection trong MongoDB, bạn cần sử dụng phương thức insert() hoặc save().

Cú pháp

Cú pháp cơ bản của lệnh insert() như sau:

>db.COLLECTION_NAME.insert(document)

Ví dụ

>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
})

Ở đây, mycol là tên của Collection, đã được tạo trong chương trước. Nếu Collection này chưa tồn tại trong cơ sở dữ liệu, thì MongoDB sẽ tạo Collection này và sau đó chèn Document vào trong nó.

Trong Document được chèn, nếu chúng ta không xác định tham số _id, thì MongoDB gán một ObjectId duy nhất cho Document này.

_id là một số thập lục phân duy nhất, dài 12 byte cho mỗi Document trong một Collection. 12 byte được phân chia như sau (đã được mô tả trong các chương trước):

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

Để chèn nhiều Document trong một truy vấn đơn, bạn có thể truyền một mảng các Document trong lệnh insert().

Ví dụ

>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 
      }
   ]
}
])

Để chèn dữ liệu vào trong Document, bạn cũng có thể sử dụng db.post.save(document). Nếu bạn không xác định _id trong Document, thì phương thức save() sẽ làm việc giống như phương thức insert(). Nếu bạn xác định _id, thì nó sẽ thay thế toàn bộ dữ liệu của Document chứa _id khi được xác định trong phương thức save().

Leave a Reply

Your email address will not be published. Required fields are marked *

bujangjp slotsensa slot88 slot4d slot4d slot4d sv388 slot88 suhubet demo slot slot4d demo slot https://fabritec.pe/asesor.php suhubet bujangjp https://kibf.pk/ slotsensa buku303 slot4d sbobet slot gacor slot gacor slot gacor totogacor slot thailand slot thailand slot gacor slot luar negeri slot gacor 4d totogacor slot gacor wd jutaan slotsensa slot gacor slot gacor slotsensa slot gacor slot dana slot dana https://cliffcrestinn.com/ totogacor totogacor demo slot slot 4d totogacor totogacor demo slot totogacor slot thailand totogacor bujangjp situs gacor 4D situs gacor Situs Gacor 4D Thailand Situs Gacor 4D SLOT4D bujangjp