• Home
  • About
    • Hanna's Blog photo

      Hanna's Blog

      I wanna be a global developer.

    • Learn More
    • Email
    • LinkedIn
    • Github
  • Posts
    • All Posts
    • All Tags
  • Projects

[MongoDB] MongoDB Practice

03 Oct 2022

Reading time ~2 minutes

IDE

Download

  • Download MongoDB for VSCode in Visual Studio Code
IDE

Create Cluster

  • Create Cluster on MongoDB Web
IDE

Connection

  • Click Connection button on Mongo DB web and check your cluster connection string.
  • Click MongoDb Playground on side bar.
  • Connect your cluster in VSCode with your connection string.
Connection
  • Change the name
Connection

Playground

  • Create new Playground to add your script.
Connection

IRUD

Insert

  • use switchs current database.
  • db.{collection} accesses to the collection.
  • insertOne inserts one document on your collection.
use('video');

var movie = {"title" : "Star Wars: Episode IV - A New Hope" ,
    "director" : "George Lucas",
    "year" : 1977};

db.movies.insertOne(movie);
IRUD
  • insertMany inserts many document on your collection.
db.movies.insertMany([{"title" : "Ghostbusters"}, 
    {"title" : "E.T"}, 
    {"title" : "Blade Runner"}]);
IRUD

Read

  • find shows all documents.
db.movies.find().pretty();
IRUD
  • findOne shows only one document.
db.movies.findOne();
IRUD

Update

  • updateOne updates one document.
db.movies.updateOne({title : "Star Wars: Episode IV - A New Hope"}, 
    {$set : {reviews:[]}});
IRUD

Delete

  • deleteOne deletes one document.
db.movies.deleteOne({title : "Star Wars: Episode IV - A New Hope"});
IRUD
  • deleteMany deletes many documents.
IRUD
  • deleteMany({}) deletes all documents.
IRUD

Drop

  • drop drops the collection.

Blocking

db.dropDatabase = DB.prototype.dropDatabase = no; // block to delete database
DBCollection.prototype.drop = no; // block to delete collection
DBCollection.prototype.dropIndex = no; // block to delete Index
DBCollection.prototype.dropIndexes = no; // block to delete Indexes

Document

Replace

  • replaceOne changes database version.
Document

Modifier

  • $inc increase field value.
Document
  • $set set field value.
  • $unset remove field from the document.
Document
Document
  • $push adds element or create new array.
  • $each adds elements at once.
  • $slice limits the array size.
  • $sort sorts elements with the field value.
  • $each is always needed when you use $push with $slice or $sort.
Document
Document
Document
  • $ne finds documents which don’t have not specific value.
Document
  • $addToSet add specific value without duplication.
Document
  • $ne/$push can add only one value and $addToSet/$each can add several values at once.
Document
  • $pop removes array elements like stack or queue.
  • {"$pop" : {"key" : 1}} removes elements from last.
  • {"$pop" : {"key" : -1}} removes elements from first.
Document
  • $pull removes array elements with specific conditions.
Document


MongoDBDBNoSQL Share Tweet +1