MongoDB - Create a Document

MongoDB provides the insert() method (and two others) for adding documents to a database.

MongoDB provides the following three methods for inserting documents into a database:

The insert() Method

The insert() method inserts one or more documents into a collection. Each document is provided as a parameter. The collection name is prepended to the insert() method.

Here's the syntax for inserting a single document:

In the above example, the document consists of { name: "value" }. This is a JSON document. JSON documents consist of one or more name/value pairs, enclosed in curly braces {}.

MongoDB uses JSON documents to store data, so that's why we insert documents in this format.

We've already used this method previously when we created a database.

Let's add another document to our database:

This inserts a document with { artistname: "Jorn Lande" } as its contents.

Now, if we search the artists collection, we will see two documents (including the one we created previously):

> db.artists.find()
{ "_id" : ObjectId("5780fbf948ef8c6b3ffb0149"), "artistname" : "The Tea Party" }
{ "_id" : ObjectId("5781c9ac48ef8c6b3ffb014a"), "artistname" : "Jorn Lande" }

Note that MongoDB has created an _id field for the documents. If you don't specify one, MongoDB will create one for you. However, you can provide this field when doing the insert if you prefer to have control over the value of the _id field.

Result:

> db.artists.find()
{ "_id" : ObjectId("5780fbf948ef8c6b3ffb0149"), "artistname" : "The Tea Party" }
{ "_id" : ObjectId("5781c9ac48ef8c6b3ffb014a"), "artistname" : "Jorn Lande" }
{ "_id" : 1, "artistname" : "AC/DC" }

The _id that MongoDB provides is a 12-byte ObjectId value. It is made up of the following values;

Create Multiple Documents

You can insert multiple documents within a single insert() method.

In this example, we insert three documents:

Note that the documents are provided as an array. The documents are enclosed in square brackets [], and they are separated by commas.

Running the above code results in the following message:

BulkWriteResult({
	"writeErrors" : [ ],
	"writeConcernErrors" : [ ],
	"nInserted" : 3,
	"nUpserted" : 0,
	"nMatched" : 0,
	"nModified" : 0,
	"nRemoved" : 0,
	"upserted" : [ ]
})

Embedded Documents

A document can contain other documents, arrays, and arrays of documents.

You can also provide multiple name/value pairs within a document by separating them with a comma.

Result:

WriteResult({ "nInserted" : 1 })

Parameters

The insert() method accepts the following parameters.

ParameterTypeDescription
document document or array A document or array of documents to insert into the collection (as in the above examples).
writeConcern document Optional parameter. This is a document expressing the write concern. A write concern describes the level of acknowledgement requested from MongoDB for write operations to a standalone mongod or to replica sets or to sharded clusters.
ordered boolean Optional parameter. If the value is set to true, MongoDB will perform an ordered insert of the documents in the array, and if an error occurs with one of documents, MongoDB will return without processing the remaining documents in the array.

If the value is set to false, MongoDB will perform an unordered insert, and if an error occurs with one of documents, the remaining documents in the array will continue to be processed.

The insertOne() Method

You can also use the insertOne() method to insert a single document into a collection:

Here, we've specified a non-existent collection. As with the insert() method, the specified collection will be created if it doesn't already exist.

You'll notice that the output is different to when you use the insert() method:

{ "acknowledged" : true, "insertedId" : 1 }

Embedded Documents

As with insert(), you can insert embedded documents and arrays of documents:

Result:

{
	"acknowledged" : true,
	"insertedId" : ObjectId("578214f048ef8c6b3ffb0159")
}

The insertMany() Method

As the name suggests, you can use insertMany() to insert multiple documents:

Again, the output when using insertMany() is different than if you'd inserted multiple documents using the insert() method:

{
	"acknowledged" : true,
	"insertedIds" : [
		2,
		3,
		4,
		5,
		6,
		7,
		8
	]
}

Embedded Documents

Result:

{
	"acknowledged" : true,
	"insertedIds" : [
		ObjectId("578217c248ef8c6b3ffb015a"),
		ObjectId("578217c248ef8c6b3ffb015b")
	]
}