How to Create Documents in MongoDB

MongoDB is a NoSQL database that stores unique data such as documents, which are grouped into collections. For example, in a MongoDB database, each customer’s data is stored as a document, and all the customer documents are stored in a collection.

In this tutorial article, you’ll learn how to create documents in MongoDB.

MongoDB Create Operations

MongoDB has two create operations—insertOne() and insertMany(). Each create operation is restricted to manipulating a single collection per execution. However, you can insert one, or many documents on each execution.

 

Therefore, both create operations have the following structure:

db.collection.createOperation()

Where db is the name of the database, and createOperation() is the appropriate operation (insertOne () or insertMany()).

Using the insertOne() Operation

The insertOne() operation inserts a single document into a collection, using the following code:

db.collection(‘customers’).insertOne({
name: “Sarah Wilson”,
age: 22
})

If there’s a problem creating the new document, the insertOne() operation returns an error. And if the collection you’re trying to add a document to doesn’t exist, MongoDB will create the collection and add the document to it.

You should notice that there’s no ID assigned to the document. This is because MongoDB automatically creates a unique ID for each document in a collection.

Using the insertMany() Operation

The insertMany() operation works in much the same way as the insertOne() operation. It creates a new collection if the one provided doesn’t exist, and it returns an error if there’s a problem creating a new document.

However, the main difference is that the insertMany() operation allows you to create multiple documents per execution.

Using the insertMany() Operation Example

db.collection(‘customers’).insertMany({
name: “Roy Williams”,
age: 21
},
{
name: “James Brown”,
age: 38
},
{
name: “Jessica Jones”,
age: 25
})

The example above creates three documents in the customer collection, and each document is separated with a comma.

Explore the Other CRUD Operations

Creating new documents is only the beginning of what you can do with MongoDB. MongoDB allows you to perform the CRUD operations, so you can develop complete databases.

Releated

How to Work Effectively With Dates and Times in MySQL

Dates and times are important, they help keep things organized, and are an integral aspect of any software operation. Efficiently working with them within the database can sometimes seem confusing, whether it’s working across the various time zones, adding / subtracting dates, and other operations. Learn the various MySQL functions available to easily handle and […]