DEV Community

Ahmad
Ahmad

Posted on

Guide to MongoDb

Introduction -

Brief database description -
A database is a structured, organised, collection of data used for storage, retrieval, management, and manipulation of data.

SQL -
Traditionally this is done with what is called an SQL (Structured Query Language). This language allows users to communicate with relational databases such as MySQL, Postgres, SQLite, etc. A relational database is a database that organises data into rows and columns, creating relationships between datapoints.

SQL databases are the right choice for many applications, but they can take time to prepare, and though they are easy to scale onto bigger servers, they are challenging to scale across multiple servers due to them being “rigid”, maintaining strong data consistency, and managing complex join operations.

Enter MongoDB -

What is MongoDB? -
A good alternative to SQL databases is MongoDB, an open-source, document oriented, NoSQL database.

Why use it? -
NoSQL means that relational tables aren’t used, and instead other formats such as key-value pairs, graphs, and documents are used. These formats are much more flexible and can easily store a wide variety of data, and due to them being non-relational NoSQL databases can be significantly faster and easier to design, update, and scale (vertically and horizontally).

Making a MongoDB database -

Installation options -
MongoDB can be either locally installed or set up in the cloud through MongoDB Atlas.
Why MongoDB Atlas is preferred -
Installing locally means one would have to maintain and upkeep the system, but MongoDB Atlas is a fully managed database-as-a-server where database clusters, a group of interconnected servers, can be created using AWS, Azure, or Google Cloud.

How to use your database -

Creating a cluster -
Sign up. To access MongoDB Atlas, go to https://www.mongodb.com/cloud/atlas/register and you will be prompted to sign up.
Create a database cluster. You will have the ability to choose a subscription plan, a provider, a region, and tags for categorization.
Connect to your cluster. The steps to doing this include setting up a connection security, choosing a connect method, and finally connecting.

Receiving and displaying data -
This code should be placed in a js file to import and connect to your database.

const { MongoClient, ServerApiVersion } = require('mongodb');
const uri = "mongodb+srv://aford504:Nitro0311$@mvpcluster.zrfg2f2.mongodb.net/?appName=MVPCluster";


// Create a MongoClient with a MongoClientOptions object to set the Stable API version
const client = new MongoClient(uri, {
 serverApi: {
   version: ServerApiVersion.v1,
   strict: true,
   deprecationErrors: true,
 }
});


async function run() {
 try {
   // Connect the client to the server (optional starting in v4.7)
   await client.connect();
   // Send a ping to confirm a successful connection
   await client.db("sample_mflix").command({ ping: 1 });
   console.log("Pinged your deployment. You successfully connected to MongoDB!");
   // Runs function to display data
   await findListings(client, 5);
 } finally {
   // Ensures that the client will close when you finish/error
   await client.close();
 }
}
run().catch(console.dir);
Enter fullscreen mode Exit fullscreen mode

This code receives data from the database sample_mflix’s users collection and prints it to the console.

async function findListings(client, resultsLimit) {
 const cursor = client
   .db('sample_mflix')
   .collection('users')
   .find()
   .limit(resultsLimit);


 const results = await cursor.toArray();
 if (results.length > 0) {
   console.log(`Found ${results.length} listing(s):`);
   results.forEach((result, i) => {
     date = new Date(result.last_review).toDateString();


     console.log();
     console.log(`${i + 1}. name: ${result.name}`);
     console.log(`   _id: ${result._id}`);
     console.log(`   bedrooms: ${result.bedrooms}`);
     console.log(`   bathrooms: ${result.bathrooms}`);
     console.log(
       `   most recent review date: ${new Date(
         result.last_review
       ).toDateString()}`
     );
   });
 }
}
Enter fullscreen mode Exit fullscreen mode

If sample_mflix isn’t in your cluster, then you can click the Load Sample Dataset button to create it.

Assuming you named the file mongo.js, you can now run “node mongo.js” in the terminal to see the five listings of users.

Top comments (0)