MongoDB快速入门(四)- 插入文档

插入文档

将数据插入到MongoDB集合,需要使用MongoDB 的 insert() 方法。

语法

insert()命令的基本语法如下:

>db.COLLECTION_NAME.insert(document)

例子

>db.mycol.insert({
   _id: ObjectId(7df78ad8902c),
   title: 'MongoDB Overview', 
   description: 'MongoDB is no sql database',
   by: 'yiibai tutorials',
   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: 'yiibai tutorials',
   url: 'http://www.yiibai.com',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 100
},
{
   title: 'NoSQL Database', 
   description: 'NoSQL database doesn't have tables',
   by: 'yiibai tutorials',
   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 
      }
   ]
}
])

查询文档

要从集合查询MongoDB数据,需要使用MongoDB的 find()方法。

语法

find()方法的基本语法如下

>db.COLLECTION_NAME.find()

find() 方法将在非结构化的方式显示所有的文件。 如果显示结果是格式化的,那么可以用pretty() 方法。

语法

>db.mycol.find().pretty()

例子

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

除了find()方法还有findOne()方法,仅返回一个文档。

原文地址:https://www.cnblogs.com/yang-hao/p/5379008.html