Skip to main content

MongoDB: CRUD

CRUD - Create Read Update Delete

CRUD stands for Create Read Update Delete. Those are fundamental operations used to manipulate data stored in any type of database, SQL and NoSQL.

We must first take a look at some basic commands with database and collection before diving in CRUD documents.

Show all databses

show dbs
or with anyone going from MySQL, use the following command but without semicolon at the end
show databases

Check current database

db

Change database

use <databasename>

Show colletions in a database

show collections

Create Collection

Create a new "myMovies" collection in "movieScratch" database.

Create a new collection using mongo shell

Insert documents

Insert many documents unordered

db.<CollectionName>.insertMany(
[
 {
  "key1": "value11"
  "key2": "value12"
 },
 {
  "key1": "value21"
  "key2": "value22"
 }
],
{
 ordered: false
}
)
MongoDB: Insert many documents unordered

Take a look at the result: The third document cannot be inserted due to duplicated key error with the first document.

MongoDB: Insert many documents unordered result

Read documents

Read all documents in a collection with find()

db.<CollectionName>.find()

Count all documents in a document with count()

db.<CollectionName>.count()

Count and filter specific documents in a collection.

MongoDB: Read documents in a collection with find()

Find movies that rated as "PG" and have exactly 10 nominations in "movieDetails" collection of "movie" database.

db.movieDetails.find({"rated":"PG","awards.nominations":10})
MongoDB: Yet another example of find and filter documents in a collection

To be continued...

Let's learn by blogging, it REALLY takes our times but it is worth it, at least for me.

Popular posts from this blog

Windows 10 1903 Critical Error: Your Start menu isn't working

Windows 10 1903 Critical Error: Your Start menu isn't working. We'll try to fix it the next time you sign in.

[PowerShell]: Powershell script uploading backup databases to ftp server

Author:  Enrique Puig Nouselles http://gallery.technet.microsoft.com/scriptcenter/80647f66-139c-40a4-bb7a-04a2d73d423c Nhu cầu - Học sử dụng Powershell và áp dụng vào thực tế - Server chạy MS SQL được backup mỗi ngày và lưu các file backup ở folder mặc định "C:/Program Files/Microsoft SQL Server/MSSQL11.MSSQLSERVER/MSSQL/Backup" - Upload các file database backup về một ftp server khác để lưu "offsite" # Begin script # Thanks to: Enrique Puig Nouselles http://gallery.technet.microsoft.com/scriptcenter/80647f66-139c-40a4-bb7a-04a2d73d423c # Khai báo folder chứa các file backup database, dưới đây là folder backup mặc định của MS SQL 2012 $Dir="C:/Program Files/Microsoft SQL Server/MSSQL11.MSSQLSERVER/MSSQL/Backup"   # ftp server $ftp = "ftp://IPAddres/subfolder/subsubfolder" $user = "usernamehere" $pass = "passwordhere" # DO NOT use $(Get-Date), use $d variable instead, otherwise SQL Agent gets error "The...