MongoDB 插入文档

在本章中,我们将学习如何在MongoDB集合中插入文档。

insert()方法

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

语法

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

>db.COLLECTION_NAME.insert(document)

在线示例

> db.users.insert({
... _id : ObjectId("507f191e810c19729de860ea"),
... title: "MongoDB Overview",
... description: "MongoDB is no sql database",
... by: "基础教程",
... url: "",
... tags: ['mongodb', 'database', 'NoSQL'],
... likes: 100
... })
WriteResult({ "nInserted" : 1 })
>

这是我们在上一章中创建的集合名称 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.createCollection("post")
> db.post.insert([
	{
		title: "MongoDB Overview",
		description: "MongoDB不是SQL数据库",
		by: "基础教程",
		url: "",
		tags: ["mongodb", "database", "NoSQL"],
		likes: 100
	},
	{
	title: "NoSQL Database",
	description: "NoSQL数据库没有表",
	by: "基础教程",
	url: "",
	tags: ["mongodb", "database", "NoSQL"],
	likes: 20,
	comments: [
		{
			user:"user1",
			message: "My first comment",
			dateCreated: new Date(2013,11,10,2,35),
			like: 0
		}
	]
}
])
BulkWriteResult({
	"writeErrors" : [ ],
	"writeConcernErrors" : [ ],
	"nInserted" : 2,
	"nUpserted" : 0,
	"nMatched" : 0,
	"nModified" : 0,
	"nRemoved" : 0,
	"upserted" : [ ]
})
>

要插入文档,您也可以使用db.post.save(document)。如果您未在文档中指定 _id,则 save()方法将与insert()方法相同。如果指定_id,则它将替换save()方法中指定的包含_id的文档的整个数据。

insertOne()方法

如果只需要将一个文档插入到集合中,则可以使用此方法。

语法

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

>db.COLLECTION_NAME.insertOne(document)

示例

以下示例创建一个名为 empDetails 的新集合,并使用insertOne()方法插入一个文档。

> db.createCollection("empDetails")
{ "ok" : 1 }
> db.empDetails.insertOne(
	{
		First_Name: "Radhika",
		Last_Name: "Sharma",
		Date_Of_Birth: "1995-09-26",
		e_mail: "radhika_sharma.123@gmail.com",
		phone: "9848022338"
	})
{
	"acknowledged" : true,
	"insertedId" : ObjectId("5dd62b4070fb13eec3963bea")
}
>

insertMany()方法

您可以使用insertMany()方法插入多个文档。对于此方法,您需要传递一个文档数组。

示例

以下示例使用insertMany()方法将三个不同的文档插入empDetails集合。

> db.empDetails.insertMany(
	[
		{
			First_Name: "Radhika",
			Last_Name: "Sharma",
			Date_Of_Birth: "1995-09-26",
			e_mail: "radhika_sharma.123@gmail.com",
			phone: "9000012345"
		},
		{
			First_Name: "Rachel",
			Last_Name: "Christopher",
			Date_Of_Birth: "1990-02-16",
			e_mail: "Rachel_Christopher.123@gmail.com",
			phone: "9000054321"
		},
		{
			First_Name: "Fathima",
			Last_Name: "Sheik",
			Date_Of_Birth: "1990-02-16",
			e_mail: "Fathima_Sheik.123@gmail.com",
			phone: "9000054321"
		}
	]
)
{
	"acknowledged" : true,
	"insertedIds" : [
		ObjectId("5dd631f270fb13eec3963bed"),
		ObjectId("5dd631f270fb13eec3963bee"),
		ObjectId("5dd631f270fb13eec3963bef")
	]
}
>