aparnajoshi

MongoDB: 101 - Getting Started

MongoDB has certainly grown its popularity among the NoSQL databases out there. MongoDB is a document-oriented database system that uses JSON-like documents to store data. This article quotes a brief introduction providing all the details required to get started with MongoDB database in any project.

Installation:

  • MongoDB: Please install MongoDB in your system using this link. The installation has 2 parts. The MongoDB database that runs on your operating system as a service and Mongo shell that is an interactive JavaScript interface to work with MongoDB.
  • MongoDB Compass: Compass is a GUI that represents data present in your MongoDB database in a user-friendly way. This interface also allows you to query data, view it, update the data, and inspect its structure. Once you launch compass, provide the local database URL mongodb://localhost:27017/ and hit CONNECT. This should show the default DBs present. Once the compass is connected, this is how it represents your databases and collections.

compass

The schema under a given collection in MongoDB compass represents different types of data present and their distribution.

compass-schema

Note that by default all the data is stored under the folder /db/data. This can be changed by providing --dbpath when starting the service.

Create DB, Collection

To create a new database simple use the command:

use exampledb

This command creates the database and also loads it under db variable.

List your dbs, using this command:

show dbs

List collections under the given database, use this command:

show collections

CRUD operations in MongoDB

Note that if you are using NodeJs to connect to your DB, this exact code can be used in your project to perform any of these operations.

  • Create: Create operation selects a particular collection under a given database and adds an entry to it. If the collection is not present, it simply creates the collection and adds data. Every entry in the collection should have a unique key. This key is automatically created when an entry is inserted into the collection under the name _id. Note that MongoDB insert would fail if the keys that are marked to be unique are duplicated.
// example - Add a single entry in a collection
use `<dbname>`
db.`<collectionname>`.insertOne({
  title: "Star trek",
  year: 1982
})

// result
{
	"acknowledged" : true,
	"insertedId" : ObjectId("5f468855ff5e6c2525281024")
}
//  example - Add multiple entries in a collection
use `<dbname>`
db.`<collectionname>`.insertMany([
  {
    title: "Star trek",
    year: 1982
  },
  {
    title: "Star wars",
    year: 1983
  }
])

// result
{
	"acknowledged" : true,
	"insertedIds" : [
		ObjectId("5f46887bff5e6c2525281025"),
		ObjectId("5f46887bff5e6c2525281026")
	]
}
  • Read: Read operation selects a particular collection under a given database and retrieves the data based on a given set of conditions. If the collection is not present or the condition is not met, no data is provided.
// example - Read from a collection
use `<dbname>`
db.`<collectionname>`.find({title: "Star trek"})
// result
{ "_id" : ObjectId("5f468855ff5e6c2525281024"), "title" : "Star trek", "year" : 1982 }
{ "_id" : ObjectId("5f46887bff5e6c2525281025"), "title" : "Star trek", "year" : 1982 }
  • Update: As the name suggests the operation selects an entry under a collection and updates its value. It also returns how many items under the collection was updated.
// example - Update single entry in a collection
use `<dbname>`
db.`<collectionname>`.updateOne(
  {title: "The Martian"},
  {
    $set: {
      poster: "poster details"
    }
  })

//result
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
// example - Update multiple entries in a collection
use `<dbname>`
db.`<collectionname>`.updateMany(
  {rated: null},
  {
    $set: {
      rated: "5"
    }
  })
{ "acknowledged" : true, "matchedCount" : 4, "modifiedCount" : 4 }
  • Delete: Delete operation deletes an entry in a collection based on the given condition. It also returns how many items under the collection was updated. It returns the number of items that got deleted from the operation performed.
// example - Delete a single entry in a collection
use `<dbname>`
db.`<collectionname>`.deleteOne({_id: ObjectId("5828035230585")})

//result 
{ "acknowledged" : true, "deletedCount" : 1 }
// example - Deletes a multiple entries in a collection
use `<dbname>`
db.`<collectionname>`.deleteMany({year: 1957})

//result
{ "acknowledged" : true, "deletedCount" : 3 }

You can use these CRUD operations to interact with your database and collections. This is only the tip of an iceberg called MongoDB. Several query operations can be performed on your data. To learn more on MongoDB you can visit: https://university.mongodb.com/


Aparna Joshi

Written by Aparna Joshi who works as a software engineer in Bangalore. Aparna is also a technology enthusiast, writer, and artist. She has an immense passion and curiosity towards psychology and its implications on human behavior. Her links: Blog, Twitter, Email, Newsletter