在本章中,我们将学习如何在mongodb集合中插入文档。
要将数据插入到 mongodb 集合中,需要使用 mongodb 的 insert()
或save()
方法。
语法
insert()
命令的基本语法如下:
>db.collection_name.insert(document)
示例
>db.mycol.insert({
_id: 100,
title: 'mongodb overview',
description: 'mongodb is no sql database',
by: 'h3 tutorials',
url: 'http://www.h3.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.mycol.insert([
{
_id: 101,
title: 'mongodb guide',
description: 'mongodb is no sql database',
by: 'h3 tutorials',
url: 'http://www.h3.com',
tags: ['mongodb', 'database', 'nosql'],
likes: 100
},
{
_id: 102,
title: 'nosql database',
description: "nosql database doesn't have tables",
by: 'h3 tutorials',
url: 'http://www.h3.com',
tags: ['mongodb', 'database', 'nosql'],
likes: 210,
comments: [
{
user:'user1',
message: 'my first comment',
datecreated: new date(2017,11,10,2,35),
like: 0
}
]
},
{
_id: 104,
title: 'python quick guide',
description: "python quick start ",
by: 'h3 tutorials',
url: 'http://www.h3.com',
tags: ['python', 'database', 'nosql'],
likes: 30,
comments: [
{
user:'user1',
message: 'my first comment',
datecreated: new date(2018,11,10,2,35),
like: 590
}
]
}
])
要插入文档,也可以使用db.post.save(document)
。 如果不在文档中指定_id
,那么save()
方法将与insert()
方法一样自动分配id的值。如果指定_id
,则将以save()
方法的形式替换包含_id
的文档的全部数据。
db.collection.insertone()
方法将单个文档插入到集合中。以下示例将新文档插入到库存集合中。 如果文档没有指定_id
字段,mongodb会自动将_id
字段与objectid
值添加到新文档。
db.inventory.insertone(
{ item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } }
)
db.collection.insertone()
方法返回包含新插入的文档的`_id```字段值的文档。
执行结果如下 -
> db.inventory.insertone(
... { item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } }
... )
{
"acknowledged" : true,
"insertedid" : objectid("5955220846be576f199feb55")
}
>
db.collection.insertmany()
方法将多个文档插入到集合中,可将一系列文档传递给db.collection.insertmany()
方法。以下示例将三个新文档插入到库存集合中。如果文档没有指定_id
字段,mongodb会向每个文档添加一个objectid值的_id
字段。
db.inventory.insertmany([
{ item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } },
{ item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } },
{ item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } }
])
insertmany()
返回包含新插入的文档_id
字段值的文档。执行结果如下 -
> db.inventory.insertmany([
... { item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } },
... { item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } },
... { item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } }
... ])
{
"acknowledged" : true,
"insertedids" : [
objectid("59552c1c46be576f199feb56"),
objectid("59552c1c46be576f199feb57"),
objectid("59552c1c46be576f199feb58")
]
}
>