Setting up MongoDB, creating a database, collection & inserting records

Getting started with MongoDB is pretty straight forward. The first thing to do is to setup a free Mongo cluster at: https://cloud.mongodb.com/. From here, you can quite easily setup a cluster to develop against.

Before you can connect to your newly created cluster, you need to install the MongoDB shell. Which on Mac, you can do using: brew install mongodb/brew/mongodb-community-shell

Now that’s installed, you can enter the following into the terminal: mongo “mongodb+srv://yourdetails.mongodb.net/test” –username youruser. You should see something like the below:

Creating a database

It’s important to note that unlike SQL, MongoDB does not have a CREATE DATABASE function. Rather, you just switch to use a database that does not currently exist.

Creating a collection

There are a number of different options you can use when creating a collection within MongoDB, they’re documented here. In the example below we create a fixed size collection. This means, that it will automatically overwrite the oldest entries when it reaches its maximum size.

db.createCollection(“mongo”,{ capped : true, size : 5242880, max : 5000 })

  • Max defines the maximum number of documents allowed in the capped creation.
  • Size defines the maximum size in bytes for the collection. If size is reached before the max number of documents, it takes precedence.

Add documents to your collection

In the below, we run db.mongo.find() and it returns no results. This is because it’s a new collection. So, we add a new docunment:

db.mongo.insertOne(
{ name: “Charlie Brown”, Age: 100, Likes: [“ice cream”, “sausages”], size: { h: 178, w: 85, measure: “metric” } }
)

When we run db.mongo.find() again, we now see our document.

Inserting one record at a time is not really ideal. So, we can also insert many, using the below command:

db.mongo.insertMany([
{ name: “Michael Smith”, Age: 25, size: { h: 130, w: 35, measure: “metric” } },
{ name: “Kimi Raikkonen”, Age: 40, Likes: [“racing”] },
{ name: “Ronald Mcdonald”, Age: 150, Likes: [“ice cream”, “burgers”, “fries”], size: { h: 180, w: 105, measure: “metric” } }
])

Share the Post:

Related Posts