Full-Stack Web Development with Vue.js and Node

(singke) #1
Introducing MEVN Chapter 1

Creating documents

Now, let's quickly review the commands used in MongoDB. The insert command is used


to create new documents in a collection in MongoDB. Let's add a new record to the


database that we just created called posts.


Here as well, in order to add a document to a collection, we first need a collection, which


we don't have yet. But MongoDB allows us to create a collection easily by running the
insert command. Again, if the collection exists, it will add the document to the given


collection and, if the collection does not exist, it will simply create a new collection.


Now, in the Mongo shell, run the following command:


> db.posts.insertOne({
title: 'MEVN',
description: 'Yet another Javascript full stack technology'
});

The command will create a new collection called posts in the posts database. The output


of this command is:


It will return a JSON object that has the ID of the document that we just created in the


insertedId key and a flag that the event was received as acknowledged.


Fetching documents

This command is used when we want to fetch the records from a collection. We can either
fetch all the records or a specific document by passing parameters as well. We can add a


few more documents to the posts database to better learn the command

Free download pdf