发布于 2015-06-22 04:05:56 | 407 次阅读 | 评论: 0 | 来源: 网络整理

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.phperz.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.phperz.com',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 100
},
{
   title: 'NoSQL Database', 
   description: 'NoSQL database doesn't have tables',
   by: 'tutorials point',
   url: 'http://www.phperz.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()方法。 

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务