MongoDB - SZ559/-MongoDB-Learning GitHub Wiki

Introduction of MongoDB

Source: https://www.youtube.com/watch?v=FH4XRY6h8Fg&list=PLS1QulWo1RIZtR6bncmSaH8fB81oRl6MP&index=6

  • Non-relational database (NoSQL database): collections of data are not related with each other;
  • Schema-free.Based database BSON(Binary JSON)
  • Organized in gourp of documents -> collections
  • Auto-Sharding in order to scale horizontally
  • Simple query language. Rich, document-based queries: Query language (QL) refers to any computer programming language that requests and retrieves data from database and information systems by sending queries.
  • Open sources.

MongoDB vs. RDBMS

  • Collection vs. table
  • Document vs. row
  • Field vs. column
  • Schema-less

Command

Create Database

  • use mydb //if mydb is presented, switch to mydb. otherwise, create db first and switch to it.
  • db //show the current db
  • show dbs //list all presented db, database does not contains document will not be listed
  • db.collectionName.insert({"key":"value"}) //insert data into database, notice that db represents the current db, like branch in git.

Drop Database

  • use mydb
  • db.dropDatabase()

Create Collection

  • use mydb
  • db.createCollection(name,[opt])//for example: db.createCollection("myCollection"), create a collection, collection name should be a valid type: string.
  • db.collectionName.insert({"key":"value"}) //if collection existed, insert the document into the collection. Otherwise, create a new collection named collectionName and insert the document into it.
  • show collections

Drop Collection

  • db.collectionName.drop();

Insert Document

  • use school //create a datbase named school
  • db.students.insert({}) //create a collection named students; format inside the brasket is JSON, one brasket represent one document, for example: {"StudentNo":"1", "Name":"Max", "Age": 5}
  • db.students.insert([{},{},{}]) //insert mutiple documents

Query Document

  • use school
  • db.students.find().pretty() //return all documents in the collection students
  •                         //pretty is to transform the display format into the JSON format
    
  •                         //MongoDB will create an unique id for each document if the id is not assgined
    
  • db.students.findOne() //Find first document in the database
  • db.students.find({"StudentNo":"2"}) //Find all the documents whose StudentNo is 2
  •                                 //The type must match the stored type, for example: "StudentNo":2 is wrong
    
  • db.students.find({"StudentNo":{$gt:"2"}}) //Find all documents whose StudentNo is greater than 2
  • db.students.find({"StudentNo":{$gte:"2"}}) //Find all documents whose StudentNo is greater than or equal to 2
  • db.students.find({"StudentNo":{$lt:"2"}}) //Find all documents whose StudentNo is less than 2
  • db.students.find({"StudentNo":{$lte:"2"}}) //Find all documents whose StudentNo is less than or equal to 2
  • db.students.find({"StudentNo":{$lte:"2"}}) //Find all documents whose StudentNo is not equal to 2

Query Document -And OR Conditions

  • db.students.find({"FirstName: "Mark", "Age": 10}) //And operator
  • db.students.find({$or : [{"FirstName: "Mark"}, {"Age": 10}]}) //Or operator
  • db.students.find({"FirstName: "Mark", $or[{"FirstName: "Tom"}, {"Age": 10}]}) //And and or operator

Update Document

  • use school
  • db.students.update({"_id":ObjectId("Sesfjklgj345jsjfkl")},{$set:{"LastName : "Max"}}) //update the lastname of the document whose id is Sesfjklgj345jsjfkl
  • db.students.update({"Age" : 16)},{$set:{"LastName : "Max"}}) //update the last name of first document whose age is 16
  • db.students.update({"Age" : 16)},{$set:{"LastName : "Max"}}{multi:true}) //update the last name of all documents whose age is 16
  • db.students.save({"_id":ObjectId("Sesfjklgj345jsjfkl"), "Age" : 16)}) //It search the id in the docuemnt, if the id is existed, it will update the document. Otherwise, it will create a new document with inputed information

Delete Document

use school db.students.remove({"_id":ObjectId("Sesfjklgj345jsjfkl")}) db.students.remove({"Age":16}) //remove all documents whose Age is 16 db.students.remove({"Age":16} , 1) //remove first document whose Age is 16

Projection

Projection in MongoDB means selecting only necessary data rather than selecting the whole data of a document db.collectionName.find({},{key:1}) //1 represent the boolean value, 1 is true, 0 is false db.students.find({},{"Age":1}) //Only display the _id and Age of the documents db.students.find({},{"Age":1, "_id" : 0}) //Only display the Age of the documents

Sort, Skip and Limit in MongoDB

db.students.find({},{key:1, key:1, "_id":0}) //Display documents in a set order db.students.find().limit(4) //Only display the first 4 documents db.students.find().skip(2) //Skip the first 2 documents db.students.find().skip(2).limit(3) db.students.find().sort({key:1}) //Sort the documents in acending order based on the value in key, 1 means acending order, -1 means decending order

Indexing

use temp for(i = 0; i < 10000000; i = i + 1) { db.posts.insert({"studentNo":i}) }

⚠️ **GitHub.com Fallback** ⚠️