MongoDB Cheatsheet

MongoDB

Here’s a cheat-sheet for basic database management and manipulation in MongoDB.

Check for mongo process

ps -ef | grep mongo

Show DBs

show dbs

Create & Use DB

use DATABASE_NAME

Drop DB (must switch to it)

db.dropDatabase()

Check Current DB

db

Create Collection

db.createCollection("COLLECTION_NAME")

Show Collections

show collections

Drop Collection

db.COLLECTION_NAME.drop()

Insert

db.COLLECTION_NAME.insert(document)

db.COLLECTION_NAME.insert({
   _id: ObjectId(7df78ad8902c),
   title: 'MongoDB Overview',
   description: 'MongoDB is no sql database',
   by: 'tutorials point',
   url: 'http://www.tutorialspoint.com',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 100
})

db.COLLECTION_NAME.insert([
   {
      title: 'MongoDB Overview',
      description: 'MongoDB is no sql database',
      by: 'tutorials point',
      url: 'http://www.tutorialspoint.com',
      tags: ['mongodb', 'database', 'NoSQL'],
      likes: 100
   },
   {
      title: 'NoSQL Database',
      description: 'NoSQL database doesn't have tables',
      by: 'tutorials point',
      url: 'http://www.tutorialspoint.com',
      tags: ['mongodb', 'database', 'NoSQL'],
      likes: 20,
      comments: [
         {
            user:'user1',
            message: 'My first comment',
            dateCreated: new Date(2013,11,10,2,35),
            like: 0
         }
      ]
   }
])

Find

db.COLLECTION_NAME.find()

Pretty Response Find

db.COLLECTION_NAME.find().pretty()

db.COLLECTION_NAME.find({key1:value1, key2:value2}).pretty()

Update

db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA)

db.COLLECTION_NAME.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB Tutorial'}})

Save

db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})

db.COLLECTION_NAME.save(
   {
      "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point New Topic",
         "by":"Tutorials Point"
   }
)