Now that we know how MongoDB identifies each individual document, let’s focus on the Create aspect of CRUD operations. Specifically, how do we start adding new documents to our collections? In MongoDB, we can use the .insertOne()
method to insert a single new document!
The syntax for the method looks as follows:
db.<collection>.insertOne( <new_document>, { writeConcern: <document>, } );
The .insertOne()
method has a single required parameter, the document to be inserted, and a second optional parameter named writeConcern
. We won’t be working with the writeConcern
parameter in this course, but more details about the parameter can be found in the official MongoDB documentation. For now, know that it’s an optional parameter that allows us to specify how we want our write requests to be acknowledged by MongoDB.
Let’s take a look at an example where we insert a single document into a videogames
collection:
db.videogames.insertOne({ title: "Elden Ring", year: 2022, company: "Fromsoftware" });
When a document is successfully inserted with .insertOne()
, the output is an object with a field named acknowledged
(related to the writeConcern
parameter we mentioned earlier) with the value true
and a field named insertedId
where the value is the _id
field for the newly inserted document. Here is what it looks like:
{ "acknowledged": true, "insertedId": ObjectId("5fd989674e6b9ceb8665c63d") }
Note that if we try to insert into a specified collection that does not exist, MongoDB will create one and insert the document into the newly created collection.
Now, let’s practice using the .insertOne()
method by returning to our listingsAndReviews
collection inside the restaurants
database.
Instructions
Connect to the restaurants
database. Then, query the listingsAndReviews
collection for all its documents to see what the structure of each document looks like.
Use the .insertOne()
method to insert a new document in the listingsAndReviews
collection with the following properties:
name: "Elvins", cuisine: "American", restaurant_id: "40564243"
Using .findOne()
, search for the document you just inserted into the collection by its restaurant_id
.