Skip to content

Instantly share code, notes, and snippets.

@rbhatia46
Last active December 20, 2017 12:23
Show Gist options
  • Save rbhatia46/1a98b75c5d40b552a2bc09bb1f837621 to your computer and use it in GitHub Desktop.
Save rbhatia46/1a98b75c5d40b552a2bc09bb1f837621 to your computer and use it in GitHub Desktop.
MongoDB Basic Commands

MongoDB Basic Commands

show dbs //Shows all the databases
use facenovel //Creates and switches to a new database called facenovel
db //Tells the current database in use

Basic Structure of a Document

{
  first_name : "John",
  last_name : "Doe",
  memberships : ["mem1","mem2"],
  address:{
    street : " 4 Main St",
    city : "Boston"
  },
  contacts : [
  {name : "Rahul", relationship:"Friend"},
  {name : "Tim", relationship:"Son"}
  ]
}

Create a user

db.createUser(
   {
     user: "Rahul",
     pwd: "password",
     roles: [ "readWrite", "dbAdmin" ]
   }
)

Create a Collection

db.createCollection('customers') 
show collections //Lists all the collections in the current database

Insert a document in a collection

db.customers.insert({firstName:"John",lastName:"Doe"})

db.customers.insert([
{firstName:"Rahul"}, {firstName:"Rahul",lastName:"Bhatia",age:34}
]);

View all the documents in a collection

db.customers.find();

db.customers.find().pretty(); //Displays in a better manner

Update the Fields

db.customers.update({firstName:"Rahul"},{firstName:"Rahul",lastName:"Bhatia",gender:"male",age:19});

SET Operator

db.customers.update({firstName:"Rahul"},{$set:{profession:"developer"}}); 

//Adds the field developer rather than replacing all the existing data

Increment Operator

db.customers.update({firstName:"Rahul"},{$inc:{age:5}});

//Increments the age of Rahul by 5 uears

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment