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.