CRUD Operations in MongoDB / Perform CRUD Operations

2:41
Hello. In this video, you'll learn how to create and insert documents into a collection in MongoDB. There are two methods that we can use to insert documents into a collection, insertOne() and insertMany(). Let's start by inserting a single document by using the insertOne() method. To use the insertOne() method, you will append it to the database and collection name like this, db.collection.insertOne(). While connected to our database called Training, we'll call the insertOne() method on the Grades collection by using db.grades.insertOne(). But what if the Grades collection doesn't exist in our database yet? Luckily, MongoDB automatically creates the collection for you when you use insertOne(). It's important to remember this when inserting data so you don't accidentally create unnecessary collections in your database. Now we pass the document that we want to insert as a parameter inside the insertOne() method. We'll run the command. The result that's returned confirms that the insertOne() statement was successful. Note that the inserted ID field tells us the [? id ?] value of our newly inserted document. Every document in a collection must have an _id field, and its value must be unique. If you don't provide an _id, like in our example, then MongoDB will automatically generate one for you. What if we want to insert more than one document at once? MongoDB has a method called insertMany(). It looks like this. As its name suggests, insertMany() inserts multiple documents. We pass in the array of documents we want to insert, each separated by a comma. Let's open the shell and examine the insertMany() expression. First, use the insertMany() method on the Grades collection with db.grades.insertMany(). Remember, insertMany() expects an array of documents, and each document must be separated by a comma. After we run the command, we'll get a message confirming that the documents have been inserted. Like insertOne(), MongoDB autogenerates a unique value for each of the new documents. Let's recap what you learned in this video. First, we inserted a single document by using the insertOne() method. Next, we inserted multiple documents, separated by commas, by using the insertMany() method. Finally, we learned that if we don't specify an [? id ?] value when inserting a document, it will be autogenerated by MongoDB. To practice this, check out our Learning Activity for this unit.