码迷,mamicode.com
首页 > 数据库 > 详细

【Mongodb教程 第六课 】MongoDB 插入文档

时间:2014-10-18 18:09:36      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:des   http   io   os   使用   sp   文件   数据   on   

insert() 方法

要插入数据到 MongoDB 集合,需要使用 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.yiibai.com‘,
   tags: [‘mongodb‘, ‘database‘, ‘NoSQL‘],
   likes: 100
})

这里 mycol  是集合的名称,如前面的教程中创建。如果集合在数据库中不存在,那么MongoDB 将创建此集合,然后把它插入文档。

插入文档中,如果我们不指定_id参数,然后MongoDB 本文档分配一个独特的ObjectId。

_id 是12个字节的十六进制数,唯一一个集合中的每个文档。 12个字节被划分如下:

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

要插入单个查询的多个文档,可以传递一个数组 insert() 命令的文件。 

示例

>db.post.insert([
{
   title: ‘MongoDB Overview‘, 
   description: ‘MongoDB is no sql database‘,
   by: ‘tutorials point‘,
   url: ‘http://www.yiibai.com‘,
   tags: [‘mongodb‘, ‘database‘, ‘NoSQL‘],
   likes: 100
},
{
   title: ‘NoSQL Database‘, 
   description: ‘NoSQL database doesn‘t have tables‘,
   by: ‘tutorials point‘,
   url: ‘http://www.yiibai.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,它会替换整个数据文件,其中包含_id 指定save()方法。 

【Mongodb教程 第六课 】MongoDB 插入文档

标签:des   http   io   os   使用   sp   文件   数据   on   

原文地址:http://www.cnblogs.com/jthb/p/4033407.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!