Array
University of Oregon

MongoDB

How to Install & Start MongoDB

Learn how to install MongoDB, how to start the server (mongod), and how to MongoDB CLI (mongo):


MongoDB is a database that allows us to store data on disk, but not in a relational format. Instead, Mongo is a document-oriented database that conceptually allows us to store objects organized as collections in the JSON format.

MongoDB stores its data in the BSON (Binary JSON) format, but we can think of it as JSON.

The mongo CLI provides a JavaScript shell, and an API for database operations.]


MongoDB as a NoSQL DB

  • MongoDB stores its data using BSON (binary JSON) format
  • MongoDB is also used to store binary data, e.g., images.

Important Terms

A MongoDB database is a set of collections

A collection is a set of documents

document is a JSON object ({ name : value } pairs)

MongoDB stores its data using BSON (binary JSON) format. MongoDB is also used to store binary data, e.g., images.

MongoDB is NoSQL database management system (vs. relational dbms).

Mongoose is a Node.js module that serves as a data modeling tool for MongoDB.


Learning the Mongo Shell

The mongo CLI provides a JavaScript shell, and an API for database operations.

Start the Mongo shell:
mongo

List the databases:
show dbs
     local    0.03125GB

Switch to a new db:
use test
     switched to db test

The mongo shell is an interactive JavaScript interface to
MongoDB. You can use the mongo shell to query and update
data as well as perform administrative operations.

var card = { "rank":"ace", "suit":"clubs" };

card
     { "rank" : “ace”, “suit” : “clubs” }

var clubs = [];

["two", "three", "four", "five"].forEach(function (rank){
 clubs.push( { "rank":rank, "suit":"clubs" } ) });

MongoDB CRUD Operations

Create new collection in and add documents:
db.cards.insert(clubs);

Retrieve all documents:
db.cards.find();

Retrieve a single document:
db.cards.find({rank:"four"})

Add a new document:
db.cards.insert({rank:"one", suit:"clubs"});
db.cards.find()

Update a document:
db.cards.update({rank:"ace"}, {rank:"ace", 
   suit:"clubs"});

Delete a document:
db.cardsColl.remove({rank:"four"});

Save vs Insert in MongoDB

  • If you use “insert” with an ID that was previously used in the same collection you will get a duplicate key error.
  • If you use “save” with an ID that is already in the same collection, it will get updated/overwritten.

To drop a database named fubar

use fubar;
db.dropDatabase();

To drop a collection named fubaz

db.fubaz.drop()

 


 

Skip to toolbar