To list the current datbase.

db

To switch to a different database.

use mydb

To insert documents (person) into a collection (people).

mo = { name: 'mo' }
  allison = { name: 'allison' }

  db.people.insert(mo)
  db.people.insert(allison)

To show all documents in a collection.

db.people.find()

To iterate over all records in a collection:

var family = db.people.find()
  while (family.hasNext()) printjson(family.next())

Query by example:

db.family.find({ name: 'mo' })

Find a single document:

db.people.findOne({name: 'allison'})

To limit the number of results returned:

db.people.find().limit(2)

You can create a .mongorc.js file which will get loaded each time you start a new mongo session. In this file you can declare functions that you want to make available to each session.

A mongo connection string looks like this:

mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
  
  mongodb://localhost/people

CRUD

Mongo stores data in the form of documents. These are JSON-like key value pairs. These documents are BSON documents. This is a binary representation of JSON with additional type information.

Mongo stores all documents in collections. A collection is a group of related documents that have a set of shared common indexes. Collections are analogous to a table in relational databases.

Query

A query targets a specific collection of documents. These specify criteria that identify documents to return. A query can include a projection that specifies the fields from the matching documents to return. You can also modify queries to impose limits, skips and sort orders.

db.users.find( { age: { $gt: 18 } } ).sort( { age: 1 } )

Data Modification

Create, Update and Delete are operations that modify the data of a single collection. For update and delete you can specify the criteria to select the documents to update or remove.

document = { name: 'mo', age: 29 }
  db.users.insert(document)

To be continued… more…

comments powered by Disqus