Skip to content

Instantly share code, notes, and snippets.

@khilnani
Last active August 29, 2015 13:56
Show Gist options
  • Save khilnani/8885023 to your computer and use it in GitHub Desktop.
Save khilnani/8885023 to your computer and use it in GitHub Desktop.
mongodb notes

Install

Tasks

  • Start Server
    • mongod --auth &
    • sudo service mongodb stop/start/restart
  • Start Server with REST API - mongod --rest
  • Web Server - 127.0.0.1:28017
  • COnnections - 127.0.0.1:27017
  • CLI - mongo
  • Config - --config /usr/local/etc/mongod.conf

User

use DBNAME  (eg. admin or test)
db.addUser('theadmin', '12345');
db.auth('theadmin','12345');

Commands

  • List DBs - show dbs
  • Switch DB - use mydb
  • Print curent DB - db
  • Set a column - j = { name : "mongo" } - k = { x : 3 }
  • Insert - db.test.insert( j )
  • Save - db.test.save( {a: 1} )
  • Find - db.test.find()
  • Show COllections - show collections
  • exit exit

Cursors

j = { name: "mongo", x: 1 }
k = { name: "Jake", x : 2 }
l = { name: "Mike", x : 3 }
db.test.insert( j )
db.test.insert( k )
db.test.insert( l )

// iterate
var c = db.test.find()
while ( c.hasNext() ) printjson( c.next() )

var c = db.test.find()
// print row 1
printjson( c [ 1 ] )

// Get al
db.test.find(  )

// Search
db.test.find( { x : 1 } )

// First result
db.test.findOne( { x : 1 } )

// limit
db.test.find( { x : 1 } ).limit(3)

// only get the 'name' - Collection / Query / Projection
db.test.find({x:1}, { name:1} )

// only with x > 1
db.test.find({x: { $gt: 1}})

// sort by x - Collection / Query / Modifier
db.test.find({x: { $gt: 1}}).sort({x:1})

c = { x: { $gt: 2} }
a = { $set: { name: "NewMike"} }
o = { multi: true }
db.test.update( c, a, o )

// replace one. if _id = update, else insert
db.test.save( { "_id":  ObjectId("52f64ae7b2897e1a48ac0793"), x: 23} )

Links

mongodb - Node.js

mongoose - Node.js

General

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